<?php
require_once 'config/db.php';
require_once 'includes/auth.php';
require_once 'includes/functions.php';
requireLogin();

$borrower_id = intval($_GET['id'] ?? 0);
if (!$borrower_id) { header('Location: /cash_lending/borrowers.php'); exit(); }
$borrower = getBorrowerById($conn, $borrower_id);
if (!$borrower) { header('Location: /cash_lending/borrowers.php'); exit(); }

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $first_name  = htmlspecialchars($_POST['first_name']  ?? '', ENT_QUOTES);
    $last_name   = htmlspecialchars($_POST['last_name']   ?? '', ENT_QUOTES);
    $address     = htmlspecialchars($_POST['address']     ?? '', ENT_QUOTES);
    $contact     = htmlspecialchars($_POST['contact']     ?? '', ENT_QUOTES);
    $id_type     = htmlspecialchars($_POST['id_type']     ?? '', ENT_QUOTES);
    $id_number   = htmlspecialchars($_POST['id_number']   ?? '', ENT_QUOTES);
    $occupation  = htmlspecialchars($_POST['occupation']  ?? '', ENT_QUOTES);
    $date_of_birth = $_POST['date_of_birth'] ?? '';

    if (empty($first_name)) $errors[] = 'First name is required';
    if (empty($last_name))  $errors[] = 'Last name is required';
    if (empty($address))    $errors[] = 'Address is required';
    if (empty($contact))    $errors[] = 'Contact is required';
    elseif (!preg_match('/^[0-9+\\-\\s()]{7,20}$/', $contact)) $errors[] = 'Contact number format is invalid';
    if (empty($id_type))    $errors[] = 'ID Type is required';
    if (empty($id_number))  $errors[] = 'ID Number is required';

    $upload_dir = 'uploads/borrowers/';
    $photo = null;
    $photo_b64 = trim($_POST['photo_base64'] ?? '');
    if ($photo_b64) {
        if (!empty($borrower['photo']) && file_exists($borrower['photo'])) unlink($borrower['photo']);
        $photo = saveBase64Image($photo_b64, 'photo', $upload_dir);
    } elseif (!empty($_FILES['photo']['name'])) {
        if (!empty($borrower['photo']) && file_exists($borrower['photo'])) unlink($borrower['photo']);
        $photo = saveUploadedFile('photo', 'photo', $upload_dir, $errors);
    }

    $id_photo = null;
    $id_b64 = trim($_POST['id_photo_base64'] ?? '');
    if ($id_b64) {
        if (!empty($borrower['id_photo']) && file_exists($borrower['id_photo'])) unlink($borrower['id_photo']);
        $id_photo = saveBase64Image($id_b64, 'id_photo', $upload_dir);
    } elseif (!empty($_FILES['id_photo']['name'])) {
        if (!empty($borrower['id_photo']) && file_exists($borrower['id_photo'])) unlink($borrower['id_photo']);
        $id_photo = saveUploadedFile('id_photo', 'id_photo', $upload_dir, $errors);
    }

    if (empty($errors)) {
        try {
            $sql = "UPDATE borrowers SET first_name=?,last_name=?,address=?,contact=?,
                    id_type=?,id_number=?,occupation=?,date_of_birth=?" .
                   ($photo    ? ",photo=?"    : "") .
                   ($id_photo ? ",id_photo=?" : "") .
                   " WHERE id=?";
            $params = [$first_name,$last_name,$address,$contact,$id_type,$id_number,$occupation,$date_of_birth];
            $types  = "ssssssss";
            if ($photo)    { $params[] = $photo;    $types .= "s"; }
            if ($id_photo) { $params[] = $id_photo; $types .= "s"; }
            $params[] = $borrower_id; $types .= "i";
            executeQuery($conn, $sql, $params, $types);
            logActivity($conn, $_SESSION['user_id'], 'edit_borrower',
                "Updated borrower: $first_name $last_name (ID $borrower_id)");
            header('Location: /cash_lending/borrowers.php?success=1');
            exit();
        } catch (Exception $e) {
            $errors[] = 'Error: '.$e->getMessage();
        }
    }
}

$initials  = urlencode($borrower['first_name'].'+'.$borrower['last_name']);
$photo_src = !empty($borrower['photo']) && file_exists($borrower['photo'])
    ? '/cash_lending/'.$borrower['photo']
    : "https://ui-avatars.com/api/?name={$initials}&size=120&background=0d6efd&color=fff&rounded=true";
$id_photo_src = !empty($borrower['id_photo']) && file_exists($borrower['id_photo'])
    ? '/cash_lending/'.$borrower['id_photo'] : '';

include 'includes/header.php';
include 'includes/sidebar.php';
?>

<!-- Camera modal -->
<div class="modal fade" id="cameraModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content" style="border-radius:16px;overflow:hidden;">
            <div class="modal-header border-0 pb-0">
                <h5 class="modal-title fw-bold" id="cameraModalTitle"><i class="fas fa-camera me-2 text-primary"></i>Take Photo</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" onclick="stopCamera()"></button>
            </div>
            <div class="modal-body text-center pt-2">
                <div id="cameraView" class="d-none">
                    <video id="cameraStream" autoplay playsinline
                           style="width:100%;border-radius:12px;background:#000;max-height:300px;object-fit:cover;"></video>
                    <div class="mt-3 d-flex gap-2 justify-content-center">
                        <button type="button" class="btn btn-secondary" onclick="flipCamera()"><i class="fas fa-sync-alt"></i> Flip</button>
                        <button type="button" class="btn btn-danger px-4" onclick="capturePhoto()"><i class="fas fa-circle"></i> Capture</button>
                    </div>
                </div>
                <div id="captureView" class="d-none">
                    <canvas id="captureCanvas" style="width:100%;border-radius:12px;max-height:300px;"></canvas>
                    <div class="mt-3 d-flex gap-2 justify-content-center">
                        <button type="button" class="btn btn-outline-secondary" onclick="retakePhoto()"><i class="fas fa-redo"></i> Retake</button>
                        <button type="button" class="btn btn-success px-4" onclick="usePhoto()"><i class="fas fa-check"></i> Use Photo</button>
                    </div>
                </div>
                <div id="cameraError" class="d-none py-4"><i class="fas fa-video-slash fa-3x text-muted mb-3"></i><p class="text-muted">Camera not accessible. Use upload instead.</p></div>
                <div id="cameraLoading"><div class="spinner-border text-primary my-4"></div><p class="text-muted">Starting camera…</p></div>
            </div>
        </div>
    </div>
</div>

<div class="row mb-4">
    <div class="col">
        <a href="/cash_lending/borrowers.php" class="btn btn-outline-secondary btn-sm mb-2">
            <i class="fas fa-arrow-left"></i> Back
        </a>
        <h3><i class="fas fa-user-edit"></i> Edit Borrower</h3>
    </div>
</div>

<div class="card shadow-sm">
<div class="card-body p-4">
<?php if (!empty($errors)): ?>
    <div class="alert alert-danger alert-dismissible fade show">
        <ul class="mb-0"><?php foreach($errors as $e): ?><li><?php echo htmlspecialchars($e); ?></li><?php endforeach; ?></ul>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<form method="POST" enctype="multipart/form-data">
    <input type="hidden" name="photo_base64"    id="photo_base64">
    <input type="hidden" name="id_photo_base64" id="id_photo_base64">

    <h6 class="fw-bold text-muted text-uppercase mb-3" style="letter-spacing:.5px;font-size:12px;">
        <i class="fas fa-images me-1"></i> Photos
    </h6>
    <div class="row g-4 mb-4">
        <!-- Borrower Photo -->
        <div class="col-md-6">
            <div class="border rounded-3 p-3 text-center h-100" style="background:#f8f9ff;">
                <div style="font-size:13px;font-weight:700;margin-bottom:12px;">
                    <i class="fas fa-user-circle text-primary me-1"></i> Borrower Photo
                </div>
                <img id="photoPreview" src="<?php echo htmlspecialchars($photo_src); ?>"
                     style="width:110px;height:110px;object-fit:cover;border-radius:50%;border:3px solid #0d6efd;margin-bottom:12px;" alt="">
                <div id="photoLabel" class="text-muted mb-3" style="font-size:12px;">
                    <?php echo !empty($borrower['photo']) ? 'Current photo' : 'No photo'; ?>
                </div>
                <div class="d-flex gap-2 justify-content-center flex-wrap">
                    <button type="button" class="btn btn-primary btn-sm" onclick="openCamera('photo')"><i class="fas fa-camera"></i> Camera</button>
                    <label class="btn btn-outline-secondary btn-sm mb-0" style="cursor:pointer;">
                        <i class="fas fa-upload"></i> Upload
                        <input type="file" id="photo" name="photo" accept="image/*" class="d-none" onchange="handleFileSelect(this,'photo')">
                    </label>
                    <button type="button" class="btn btn-outline-danger btn-sm" id="photoClearBtn" onclick="clearPhoto('photo')" <?php echo empty($borrower['photo'])?'style="display:none;"':''; ?>>
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
        </div>
        <!-- ID Photo -->
        <div class="col-md-6">
            <div class="border rounded-3 p-3 text-center h-100" style="background:#f8fff8;">
                <div style="font-size:13px;font-weight:700;margin-bottom:12px;">
                    <i class="fas fa-id-card text-success me-1"></i> ID Photo
                </div>
                <div id="idPhotoBox" style="width:100%;height:110px;border:2px dashed #adb5bd;border-radius:10px;background:#fff;display:flex;align-items:center;justify-content:center;overflow:hidden;margin-bottom:12px;">
                    <img id="idPhotoPreview" src="<?php echo htmlspecialchars($id_photo_src); ?>" alt=""
                         style="width:100%;height:100%;object-fit:cover;<?php echo $id_photo_src?'':'display:none;'; ?>border-radius:8px;">
                    <span id="idPhotoPlaceholder" style="<?php echo $id_photo_src?'display:none;':''; ?>color:#9ca3af;font-size:12px;text-align:center;">
                        <i class="fas fa-id-card fa-2x d-block mb-1" style="opacity:.3;"></i>ID front/back
                    </span>
                </div>
                <div id="idPhotoLabel" class="text-muted mb-3" style="font-size:12px;">
                    <?php echo !empty($borrower['id_photo']) ? 'Current ID photo' : 'No ID photo'; ?>
                </div>
                <div class="d-flex gap-2 justify-content-center flex-wrap">
                    <button type="button" class="btn btn-success btn-sm" onclick="openCamera('id_photo')"><i class="fas fa-camera"></i> Camera</button>
                    <label class="btn btn-outline-secondary btn-sm mb-0" style="cursor:pointer;">
                        <i class="fas fa-upload"></i> Upload
                        <input type="file" id="id_photo" name="id_photo" accept="image/*" class="d-none" onchange="handleFileSelect(this,'id_photo')">
                    </label>
                    <button type="button" class="btn btn-outline-danger btn-sm" id="idPhotoClearBtn" onclick="clearPhoto('id_photo')" <?php echo empty($borrower['id_photo'])?'style="display:none;"':''; ?>>
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <h6 class="fw-bold text-muted text-uppercase mb-3" style="letter-spacing:.5px;font-size:12px;">
        <i class="fas fa-user me-1"></i> Personal Information
    </h6>
    <div class="row">
        <div class="col-md-6 mb-3">
            <label class="form-label fw-semibold">First Name <span class="text-danger">*</span></label>
            <input type="text" class="form-control" name="first_name" required value="<?php echo htmlspecialchars($borrower['first_name']); ?>">
        </div>
        <div class="col-md-6 mb-3">
            <label class="form-label fw-semibold">Last Name <span class="text-danger">*</span></label>
            <input type="text" class="form-control" name="last_name" required value="<?php echo htmlspecialchars($borrower['last_name']); ?>">
        </div>
    </div>
    <div class="mb-3">
        <label class="form-label fw-semibold">Address <span class="text-danger">*</span></label>
        <textarea class="form-control" name="address" rows="2" required><?php echo htmlspecialchars($borrower['address']); ?></textarea>
    </div>
    <div class="row">
        <div class="col-md-4 mb-3">
            <label class="form-label fw-semibold">Contact <span class="text-danger">*</span></label>
            <input type="tel" class="form-control" name="contact" required value="<?php echo htmlspecialchars($borrower['contact']); ?>">
        </div>
        <div class="col-md-4 mb-3">
            <label class="form-label fw-semibold">Date of Birth</label>
            <input type="date" class="form-control" name="date_of_birth" value="<?php echo htmlspecialchars($borrower['date_of_birth'] ?? ''); ?>">
        </div>
        <div class="col-md-4 mb-3">
            <label class="form-label fw-semibold">Occupation</label>
            <input type="text" class="form-control" name="occupation" value="<?php echo htmlspecialchars($borrower['occupation'] ?? ''); ?>">
        </div>
    </div>

    <h6 class="fw-bold text-muted text-uppercase mb-3 mt-2" style="letter-spacing:.5px;font-size:12px;">
        <i class="fas fa-id-card me-1"></i> ID Information
    </h6>
    <div class="row">
        <div class="col-md-6 mb-3">
            <label class="form-label fw-semibold">ID Type <span class="text-danger">*</span></label>
            <select class="form-select" name="id_type" required>
                <option value="">-- Select --</option>
                <?php foreach(['SSS','GSIS','PRC','PhilHealth',"Driver's License",'Passport','National ID',"Voter's ID",'Postal ID','TIN ID'] as $t): ?>
                    <option value="<?php echo $t; ?>" <?php echo $borrower['id_type']===$t?'selected':''; ?>><?php echo $t; ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-6 mb-3">
            <label class="form-label fw-semibold">ID Number <span class="text-danger">*</span></label>
            <input type="text" class="form-control" name="id_number" required value="<?php echo htmlspecialchars($borrower['id_number']); ?>">
        </div>
    </div>

    <div class="d-flex gap-2 mt-4 pt-2 border-top">
        <button type="submit" class="btn btn-primary px-4"><i class="fas fa-save"></i> Save Changes</button>
        <a href="/cash_lending/borrowers.php" class="btn btn-outline-secondary"><i class="fas fa-times"></i> Cancel</a>
    </div>
</form>
</div>
</div>

<script>
let stream=null,currentFacing='user',activeTarget='photo';
function openCamera(target){
    activeTarget=target;
    document.getElementById('cameraModalTitle').innerHTML=`<i class="fas fa-camera me-2 text-primary"></i>${target==='photo'?'Take Borrower Photo':'Capture ID Photo'}`;
    document.getElementById('cameraView').classList.add('d-none');
    document.getElementById('captureView').classList.add('d-none');
    document.getElementById('cameraError').classList.add('d-none');
    document.getElementById('cameraLoading').classList.remove('d-none');
    new bootstrap.Modal(document.getElementById('cameraModal')).show();
    startCamera();
}
async function startCamera(){
    stopCamera();
    try{
        stream=await navigator.mediaDevices.getUserMedia({video:{facingMode:currentFacing},audio:false});
        document.getElementById('cameraStream').srcObject=stream;
        document.getElementById('cameraLoading').classList.add('d-none');
        document.getElementById('cameraView').classList.remove('d-none');
    }catch(e){
        document.getElementById('cameraLoading').classList.add('d-none');
        document.getElementById('cameraError').classList.remove('d-none');
    }
}
function flipCamera(){currentFacing=currentFacing==='user'?'environment':'user';startCamera();}
function capturePhoto(){
    const v=document.getElementById('cameraStream'),c=document.getElementById('captureCanvas');
    c.width=v.videoWidth||640;c.height=v.videoHeight||480;
    c.getContext('2d').drawImage(v,0,0,c.width,c.height);
    stopCamera();
    document.getElementById('cameraView').classList.add('d-none');
    document.getElementById('captureView').classList.remove('d-none');
}
function retakePhoto(){document.getElementById('captureView').classList.add('d-none');document.getElementById('cameraLoading').classList.remove('d-none');startCamera();}
function usePhoto(){
    const dataURL=document.getElementById('captureCanvas').toDataURL('image/jpeg',0.92);
    if(activeTarget==='photo'){
        document.getElementById('photo_base64').value=dataURL;
        document.getElementById('photoPreview').src=dataURL;
        document.getElementById('photoLabel').textContent='📸 Camera capture';
        document.getElementById('photoClearBtn').style.display='';
        document.getElementById('photo').value='';
    }else{
        document.getElementById('id_photo_base64').value=dataURL;
        document.getElementById('idPhotoPreview').src=dataURL;
        document.getElementById('idPhotoPreview').style.display='block';
        document.getElementById('idPhotoPlaceholder').style.display='none';
        document.getElementById('idPhotoLabel').textContent='📸 Camera capture';
        document.getElementById('idPhotoClearBtn').style.display='';
        document.getElementById('id_photo').value='';
    }
    bootstrap.Modal.getInstance(document.getElementById('cameraModal')).hide();
    stopCamera();
}
function stopCamera(){if(stream){stream.getTracks().forEach(t=>t.stop());stream=null;}}
function handleFileSelect(input,target){
    if(!input.files||!input.files[0])return;
    const reader=new FileReader();
    reader.onload=e=>{
        if(target==='photo'){
            document.getElementById('photoPreview').src=e.target.result;
            document.getElementById('photoLabel').textContent='📁 '+input.files[0].name;
            document.getElementById('photoClearBtn').style.display='';
            document.getElementById('photo_base64').value='';
        }else{
            document.getElementById('idPhotoPreview').src=e.target.result;
            document.getElementById('idPhotoPreview').style.display='block';
            document.getElementById('idPhotoPlaceholder').style.display='none';
            document.getElementById('idPhotoLabel').textContent='📁 '+input.files[0].name;
            document.getElementById('idPhotoClearBtn').style.display='';
            document.getElementById('id_photo_base64').value='';
        }
    };
    reader.readAsDataURL(input.files[0]);
}
function clearPhoto(target){
    if(target==='photo'){
        document.getElementById('photo_base64').value='';
        document.getElementById('photo').value='';
        document.getElementById('photoPreview').src='https://ui-avatars.com/api/?name=<?php echo urlencode($borrower["first_name"]." ".$borrower["last_name"]); ?>&size=120&background=0d6efd&color=fff&rounded=true';
        document.getElementById('photoLabel').textContent='No photo';
        document.getElementById('photoClearBtn').style.display='none';
    }else{
        document.getElementById('id_photo_base64').value='';
        document.getElementById('id_photo').value='';
        document.getElementById('idPhotoPreview').src='';
        document.getElementById('idPhotoPreview').style.display='none';
        document.getElementById('idPhotoPlaceholder').style.display='';
        document.getElementById('idPhotoLabel').textContent='No ID photo';
        document.getElementById('idPhotoClearBtn').style.display='none';
    }
}
document.getElementById('cameraModal').addEventListener('hidden.bs.modal',stopCamera);
</script>
<?php include 'includes/footer.php'; ?>
