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

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

function saveBase64Image($base64_string, $prefix, $upload_dir) {
    if (!preg_match('/^data:image\/(\w+);base64,/', $base64_string, $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,/', '', $base64_string));
    if (!$data) return null;
    if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
    $filename = $prefix . '_' . time() . '_' . uniqid() . '.' . $ext;
    file_put_contents($upload_dir . $filename, $data);
    return $upload_dir . $filename;
}

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 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 — base64 (from canvas crop) or file upload
    $photo = null;
    $photo_b64 = trim($_POST['photo_base64'] ?? '');
    if ($photo_b64) {
        $photo = saveBase64Image($photo_b64, 'photo', $upload_dir);
    } elseif (!empty($_FILES['photo']['name']) && $_FILES['photo']['error'] === 0) {
        if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
        $ext  = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
        $file = 'photo_' . time() . '_' . uniqid() . '.' . $ext;
        if (move_uploaded_file($_FILES['photo']['tmp_name'], $upload_dir . $file)) {
            $photo = $upload_dir . $file;
        }
    }

    // ID photo
    $id_photo = null;
    $id_b64 = trim($_POST['id_photo_base64'] ?? '');
    if ($id_b64) {
        $id_photo = saveBase64Image($id_b64, 'id_photo', $upload_dir);
    } elseif (!empty($_FILES['id_photo']['name']) && $_FILES['id_photo']['error'] === 0) {
        if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
        $ext  = pathinfo($_FILES['id_photo']['name'], PATHINFO_EXTENSION);
        $file = 'id_photo_' . time() . '_' . uniqid() . '.' . $ext;
        if (move_uploaded_file($_FILES['id_photo']['tmp_name'], $upload_dir . $file)) {
            $id_photo = $upload_dir . $file;
        }
    }

    if (empty($errors)) {
        try {
            $sql = "INSERT INTO borrowers
                        (first_name, last_name, address, contact, id_type, id_number,
                         occupation, date_of_birth, photo, id_photo)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            executeQuery($conn, $sql,
                [$first_name, $last_name, $address, $contact, $id_type,
                 $id_number, $occupation, $dob, $photo, $id_photo],
                "ssssssssss");
            header('Location: /cash_lending/mobile/borrowers.php?success=1');
            exit();
        } catch (Exception $e) {
            $errors[] = 'Error: ' . $e->getMessage();
        }
    }
}

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; ?>

<style>
.photo-slot {
    background: #fff;
    border-radius: 16px;
    border: 1px solid #e5e7eb;
    padding: 16px;
    margin-bottom: 14px;
}
.photo-slot-label {
    font-size: 11px;
    font-weight: 700;
    color: #6b7280;
    text-transform: uppercase;
    letter-spacing: .6px;
    margin: 0 0 14px;
}
.photo-preview-circle {
    width: 80px; height: 80px;
    border-radius: 50%;
    object-fit: cover;
    border: 3px solid #1a56db;
    flex-shrink: 0;
    background: #eff6ff;
}
.photo-preview-rect {
    width: 100%; height: 110px;
    border-radius: 12px;
    object-fit: cover;
    display: none;
    border: 2px solid #d1d5db;
}
.id-placeholder {
    width: 100%; height: 110px;
    border: 2px dashed #d1d5db;
    border-radius: 12px;
    background: #f9fafb;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #9ca3af;
    font-size: 12px;
    gap: 6px;
    margin-bottom: 12px;
}
.cam-action-row {
    display: flex;
    gap: 8px;
    flex-wrap: nowrap;
}
.cam-btn {
    flex: 1;
    padding: 10px 6px;
    border-radius: 10px;
    border: none;
    font-size: 12px;
    font-weight: 700;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 5px;
    white-space: nowrap;
    min-width: 0;
}
.cam-btn-primary  { background: #1a56db; color: #fff; }
.cam-btn-success  { background: #057a55; color: #fff; }
.cam-btn-outline  { background: #fff; color: #374151; border: 1.5px solid #d1d5db !important; }
.cam-btn-danger   { background: #fee2e2; color: #991b1b; border: 1.5px solid #fecaca !important; }
</style>

<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 class="photo-slot">
        <p class="photo-slot-label">
            <i class="fas fa-user-circle" style="color:#1a56db;"></i> Borrower Photo
        </p>
        <div style="display:flex;align-items:center;gap:14px;margin-bottom:12px;">
            <img id="photoPreview"
                 src="https://ui-avatars.com/api/?name=New&size=80&background=1a56db&color=fff&rounded=true"
                 class="photo-preview-circle" alt="Photo">
            <div>
                <p id="photoLabel" style="font-size:12px;color:#6b7280;margin:0 0 8px;">
                    No photo selected
                </p>
                <p style="font-size:11px;color:#9ca3af;margin:0;">
                    Use camera or pick from gallery
                </p>
            </div>
        </div>

        <div class="cam-action-row">
            <!-- Selfie / front camera -->
            <label class="cam-btn cam-btn-primary" title="Take selfie with front camera">
                <i class="fas fa-user"></i> Selfie
                <input type="file" name="photo" id="photoFile"
                       accept="image/*" capture="user"
                       style="display:none;" onchange="previewFile(this,'photo')">
            </label>

            <!-- Rear camera -->
            <label class="cam-btn cam-btn-primary" title="Use rear camera"
                   style="background:#1447b2;">
                <i class="fas fa-camera"></i> Camera
                <input type="file" name="photo_cam" id="photoCamFile"
                       accept="image/*" capture="environment"
                       style="display:none;" onchange="previewFile(this,'photo')">
            </label>

            <!-- Gallery -->
            <label class="cam-btn cam-btn-outline" title="Choose from gallery">
                <i class="fas fa-image"></i> Gallery
                <input type="file" name="photo_gallery" id="photoGalleryFile"
                       accept="image/*"
                       style="display:none;" onchange="previewFile(this,'photo')">
            </label>

            <!-- Clear -->
            <button type="button" id="photoClearBtn" class="cam-btn cam-btn-danger"
                    style="display:none;flex:0 0 auto;padding:10px 12px;"
                    onclick="clearSlot('photo')" title="Remove photo">
                <i class="fas fa-times"></i>
            </button>
        </div>
    </div>

    <!-- ══ ID PHOTO ══════════════════════════════════════════════════════ -->
    <div class="photo-slot">
        <p class="photo-slot-label">
            <i class="fas fa-id-card" style="color:#057a55;"></i> ID Photo
        </p>

        <div id="idPlaceholder" class="id-placeholder">
            <i class="fas fa-id-card" style="font-size:26px;opacity:.3;"></i>
            <span>ID front or back</span>
        </div>
        <img id="idPhotoPreview" class="photo-preview-rect"
             style="margin-bottom:12px;" alt="ID Photo">
        <p id="idLabel" style="font-size:12px;color:#6b7280;margin:0 0 10px;">
            No ID photo selected
        </p>

        <div class="cam-action-row">
            <!-- Rear camera for ID (best for documents) -->
            <label class="cam-btn cam-btn-success" title="Capture ID with rear camera">
                <i class="fas fa-camera"></i> Camera
                <input type="file" name="id_photo" id="idPhotoFile"
                       accept="image/*" capture="environment"
                       style="display:none;" onchange="previewFile(this,'id_photo')">
            </label>

            <!-- Gallery -->
            <label class="cam-btn cam-btn-outline" title="Choose from gallery">
                <i class="fas fa-image"></i> Gallery
                <input type="file" name="id_photo_gallery" id="idGalleryFile"
                       accept="image/*"
                       style="display:none;" onchange="previewFile(this,'id_photo')">
            </label>

            <!-- Clear -->
            <button type="button" id="idClearBtn" class="cam-btn cam-btn-danger"
                    style="display:none;flex:0 0 auto;padding:10px 12px;"
                    onclick="clearSlot('id_photo')" title="Remove ID photo">
                <i class="fas fa-times"></i>
            </button>
        </div>
    </div>

    <!-- ══ FORM FIELDS ════════════════════════════════════════════════════ -->
    <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($_POST['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($_POST['last_name'] ?? ''); ?>">
    </div>
    <div class="form-group">
        <label class="form-label">Contact Number <span class="required">*</span></label>
        <input type="tel" class="form-control" name="contact"
               placeholder="09XXXXXXXXX" required
               value="<?php echo htmlspecialchars($_POST['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($_POST['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($_POST['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($_POST['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 ($_POST['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($_POST['id_number'] ?? ''); ?>">
    </div>

    <div style="display:flex;gap:10px;margin-top:24px;">
        <button type="submit" class="btn btn-primary w-100">
            <i class="fas fa-save"></i> Save Borrower
        </button>
        <a href="/cash_lending/mobile/borrowers.php" class="btn btn-outline w-100">
            <i class="fas fa-times"></i> Cancel
        </a>
    </div>
</form>

<script>
// Active file source per slot (so we send the right file in the form)
let activePhotoInput   = null;
let activeIdPhotoInput = null;

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('photoClearBtn').style.display = '';

            // Copy file to the real "photo" input so PHP picks it up
            transferFile(input, 'photo_transfer', slot);

        } else {
            document.getElementById('idPhotoPreview').src              = e.target.result;
            document.getElementById('idPhotoPreview').style.display    = 'block';
            document.getElementById('idPlaceholder').style.display     = 'none';
            document.getElementById('idLabel').textContent             = '📷 ' + input.files[0].name;
            document.getElementById('idClearBtn').style.display        = '';

            transferFile(input, 'id_photo_transfer', slot);
        }
    };
    reader.readAsDataURL(input.files[0]);
}

// We use base64 to carry the image data reliably across multiple inputs
function transferFile(input, transferId, slot) {
    const reader = new FileReader();
    reader.onload = function(e) {
        if (slot === 'photo') {
            document.getElementById('photo_base64').value = e.target.result;
        } else {
            document.getElementById('id_photo_base64').value = e.target.result;
        }
    };
    reader.readAsDataURL(input.files[0]);
}

function clearSlot(slot) {
    if (slot === 'photo') {
        document.getElementById('photo_base64').value     = '';
        document.getElementById('photoFile').value        = '';
        document.getElementById('photoCamFile').value     = '';
        document.getElementById('photoGalleryFile').value = '';
        document.getElementById('photoPreview').src       =
            'https://ui-avatars.com/api/?name=New&size=80&background=1a56db&color=fff&rounded=true';
        document.getElementById('photoLabel').textContent = 'No photo selected';
        document.getElementById('photoClearBtn').style.display = 'none';
    } else {
        document.getElementById('id_photo_base64').value       = '';
        document.getElementById('idPhotoFile').value           = '';
        document.getElementById('idGalleryFile').value         = '';
        document.getElementById('idPhotoPreview').src          = '';
        document.getElementById('idPhotoPreview').style.display = 'none';
        document.getElementById('idPlaceholder').style.display  = 'flex';
        document.getElementById('idLabel').textContent          = 'No ID photo selected';
        document.getElementById('idClearBtn').style.display     = 'none';
    }
}
</script>

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