<?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/mobile/borrowers.php'); exit(); }
$borrower = getBorrowerById($conn, $borrower_id);
if (!$borrower) { header('Location: /cash_lending/mobile/borrowers.php'); exit(); }

$page_title = 'Edit Borrower';
$active_nav = 'borrowers';
$errors = [];

function saveBase64Image($b64,$prefix,$dir){
    if(!preg_match('/^data:image\/(\w+);base64,/',$b64,$type)) return null;
    $ext=strtolower($type[1]);
    if(!in_array($ext,['jpg','jpeg','png','gif','webp'])) return null;
    $data=base64_decode(preg_replace('/^data:image\/\w+;base64,/','',$b64));
    if(!$data) return null;
    if(!is_dir($dir)) mkdir($dir,0755,true);
    $file=$prefix.'_'.time().'_'.uniqid().'.'.$ext;
    file_put_contents($dir.$file,$data);
    return $dir.$file;
}

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);
    $dob        = $_POST['date_of_birth'] ?? '';

    if (empty($first_name)) $errors[]='First name required';
    if (empty($last_name))  $errors[]='Last name required';
    if (empty($address))    $errors[]='Address required';
    if (empty($contact))    $errors[]='Contact required';
    if (empty($id_type))    $errors[]='ID Type required';
    if (empty($id_number))  $errors[]='ID Number required';

    $upload_dir='../uploads/borrowers/';
    $photo=null; $id_photo=null;

    $pb64=trim($_POST['photo_base64']??'');
    if($pb64){
        if(!empty($borrower['photo'])&&file_exists($borrower['photo'])) unlink($borrower['photo']);
        $photo=saveBase64Image($pb64,'photo',$upload_dir);
    } elseif (!empty($_FILES['photo']['name'])&&$_FILES['photo']['error']===0) {
        if(!empty($borrower['photo'])&&file_exists($borrower['photo'])) unlink($borrower['photo']);
        $ext=pathinfo($_FILES['photo']['name'],PATHINFO_EXTENSION);
        $f='photo_'.time().'_'.uniqid().'.'.$ext;
        if(!is_dir($upload_dir)) mkdir($upload_dir,0755,true);
        move_uploaded_file($_FILES['photo']['tmp_name'],$upload_dir.$f);
        $photo=$upload_dir.$f;
    }

    $ib64=trim($_POST['id_photo_base64']??'');
    if($ib64){
        if(!empty($borrower['id_photo'])&&file_exists($borrower['id_photo'])) unlink($borrower['id_photo']);
        $id_photo=saveBase64Image($ib64,'id_photo',$upload_dir);
    } elseif (!empty($_FILES['id_photo']['name'])&&$_FILES['id_photo']['error']===0) {
        if(!empty($borrower['id_photo'])&&file_exists($borrower['id_photo'])) unlink($borrower['id_photo']);
        $ext=pathinfo($_FILES['id_photo']['name'],PATHINFO_EXTENSION);
        $f='id_photo_'.time().'_'.uniqid().'.'.$ext;
        if(!is_dir($upload_dir)) mkdir($upload_dir,0755,true);
        move_uploaded_file($_FILES['id_photo']['tmp_name'],$upload_dir.$f);
        $id_photo=$upload_dir.$f;
    }

    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,$dob];
            $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);
            header('Location: /cash_lending/mobile/borrower-details.php?id='.$borrower_id.'&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=90&background=1a56db&color=fff&rounded=true";
$id_src=!empty($borrower['id_photo'])&&file_exists($borrower['id_photo'])
    ?'/cash_lending/'.$borrower['id_photo']:'';

include 'header.php';
?>


<?php if (!empty($errors)): ?>
    <div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> <?php echo implode('<br>',array_map('htmlspecialchars',$errors)); ?></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">

    <!-- Borrower Photo -->
    <div style="background:var(--surface);border-radius:var(--radius);border:1px solid var(--border);padding:16px;margin-bottom:12px;text-align:center;">
        <div style="font-size:12px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.5px;margin-bottom:12px;">
            <i class="fas fa-user-circle" style="color:var(--primary);"></i> Borrower Photo
        </div>
        <img id="photoPreview" src="<?php echo htmlspecialchars($photo_src); ?>"
             style="width:90px;height:90px;border-radius:50%;object-fit:cover;border:3px solid var(--primary);margin-bottom:10px;" alt="">
        <div id="photoLabel" style="font-size:12px;color:var(--muted);margin-bottom:12px;">
            <?php echo !empty($borrower['photo'])?'Current photo':'No photo'; ?>
        </div>
        <div style="display:flex;gap:8px;flex-wrap:nowrap;">
            <label style="flex:1;padding:9px 6px;border-radius:10px;border:none;background:#1a56db;color:#fff;font-size:12px;font-weight:700;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:5px;">
                <i class="fas fa-user"></i> Selfie
                <input type="file" accept="image/*" capture="user" style="display:none;" onchange="previewFile(this,'photo')">
            </label>
            <label style="flex:1;padding:9px 6px;border-radius:10px;border:none;background:#1447b2;color:#fff;font-size:12px;font-weight:700;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:5px;">
                <i class="fas fa-camera"></i> Camera
                <input type="file" accept="image/*" capture="environment" style="display:none;" onchange="previewFile(this,'photo')">
            </label>
            <label style="flex:1;padding:9px 6px;border-radius:10px;border:1.5px solid #d1d5db;background:#fff;color:#374151;font-size:12px;font-weight:700;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:5px;">
                <i class="fas fa-image"></i> Gallery
                <input type="file" id="photo" name="photo" accept="image/*" style="display:none;" onchange="previewFile(this,'photo')">
            </label>
        </div>
    </div>

    <!-- ID Photo -->
    <div style="background:var(--surface);border-radius:var(--radius);border:1px solid var(--border);padding:16px;margin-bottom:16px;text-align:center;">
        <div style="font-size:12px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.5px;margin-bottom:12px;">
            <i class="fas fa-id-card" style="color:var(--success);"></i> ID Photo
        </div>
        <div style="width:100%;height:90px;border:2px dashed #d1d5db;border-radius:10px;background:#f9fafb;display:flex;align-items:center;justify-content:center;overflow:hidden;margin-bottom:10px;">
            <img id="idPhotoPreview" src="<?php echo htmlspecialchars($id_src); ?>" alt=""
                 style="width:100%;height:100%;object-fit:cover;<?php echo $id_src?'':'display:none;'; ?>border-radius:8px;">
            <span id="idPhotoPlaceholder" style="<?php echo $id_src?'display:none;':''; ?>color:#9ca3af;font-size:12px;text-align:center;">
                <i class="fas fa-id-card" style="font-size:22px;display:block;opacity:.3;margin-bottom:4px;"></i>ID photo
            </span>
        </div>
        <div id="idLabel" style="font-size:12px;color:var(--muted);margin-bottom:12px;">
            <?php echo !empty($borrower['id_photo'])?'Current ID photo':'No ID photo'; ?>
        </div>
        <div style="display:flex;gap:8px;flex-wrap:nowrap;">
            <label style="flex:1;padding:9px 6px;border-radius:10px;border:none;background:#057a55;color:#fff;font-size:12px;font-weight:700;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:5px;">
                <i class="fas fa-camera"></i> Camera
                <input type="file" accept="image/*" capture="environment" style="display:none;" onchange="previewFile(this,'id_photo')">
            </label>
            <label style="flex:1;padding:9px 6px;border-radius:10px;border:1.5px solid #d1d5db;background:#fff;color:#374151;font-size:12px;font-weight:700;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:5px;">
                <i class="fas fa-image"></i> Gallery
                <input type="file" id="id_photo" name="id_photo" accept="image/*" style="display:none;" onchange="previewFile(this,'id_photo')">
            </label>
        </div>
    </div>

    <div class="form-group"><label class="form-label">First Name <span class="required">*</span></label>
        <input type="text" class="form-control" name="first_name" required value="<?php echo htmlspecialchars($borrower['first_name']); ?>"></div>
    <div class="form-group"><label class="form-label">Last Name <span class="required">*</span></label>
        <input type="text" class="form-control" name="last_name" required value="<?php echo htmlspecialchars($borrower['last_name']); ?>"></div>
    <div class="form-group"><label class="form-label">Contact <span class="required">*</span></label>
        <input type="tel" class="form-control" name="contact" required value="<?php echo htmlspecialchars($borrower['contact']); ?>"></div>
    <div class="form-group"><label class="form-label">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="form-group"><label class="form-label">Address <span class="required">*</span></label>
        <textarea class="form-control" name="address" required><?php echo htmlspecialchars($borrower['address']); ?></textarea></div>
    <div class="form-group"><label class="form-label">Occupation</label>
        <input type="text" class="form-control" name="occupation" value="<?php echo htmlspecialchars($borrower['occupation']??''); ?>"></div>
    <div class="form-group"><label class="form-label">ID Type <span class="required">*</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="form-group"><label class="form-label">ID Number <span class="required">*</span></label>
        <input type="text" class="form-control" name="id_number" required value="<?php echo htmlspecialchars($borrower['id_number']); ?>"></div>

    <div style="display:flex;gap:10px;margin-top:20px;">
        <button type="submit" class="btn btn-primary w-100"><i class="fas fa-save"></i> Save</button>
        <a href="/cash_lending/mobile/borrower-details.php?id=<?php echo $borrower_id; ?>" class="btn btn-outline w-100"><i class="fas fa-times"></i> Cancel</a>
    </div>
</form>

<script>
function previewFile(input, slot) {
    if (!input.files || !input.files[0]) return;
    const reader = new FileReader();
    reader.onload = function(e) {
        if (slot === 'photo') {
            document.getElementById('photoPreview').src       = e.target.result;
            document.getElementById('photoLabel').textContent = '📷 ' + input.files[0].name;
            document.getElementById('photo_base64').value     = e.target.result;
        } else {
            document.getElementById('idPhotoPreview').src              = e.target.result;
            document.getElementById('idPhotoPreview').style.display    = 'block';
            document.getElementById('idPhotoPlaceholder').style.display = 'none';
            document.getElementById('idLabel').textContent             = '📷 ' + input.files[0].name;
            document.getElementById('id_photo_base64').value           = e.target.result;
        }
    };
    reader.readAsDataURL(input.files[0]);
}
</script>

<?php include 'footer.php'; ?>