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

requireLogin();

$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);

    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 number is required';
    elseif (!preg_match('/^[0-9+\-\s()]{7,20}$/', $contact)) $errors[] = 'Contact number format is invalid (digits, +, -, spaces only)';
    elseif (!preg_match('/^[0-9+\-\s()]{7,20}$/', $contact)) $errors[] = 'Contact number format is invalid (digits, spaces, +, - only)';
    if (empty($id_type))    $errors[] = 'ID type is required';
    if (empty($id_number))  $errors[] = 'ID number is required';

    $upload_dir = 'uploads/borrowers/';

    // ── Borrower photo ────────────────────────────────────────────────────
    $photo = null;
    $photo_b64 = trim($_POST['photo_base64'] ?? '');
    if ($photo_b64) {
        $photo = saveBase64Image($photo_b64, 'photo', $upload_dir);
        if (!$photo) $errors[] = 'Captured photo could not be saved';
    } else {
        $photo = saveUploadedFile('photo', 'photo', $upload_dir, $errors);
    }

    // ── ID photo ─────────────────────────────────────────────────────────
    $id_photo = null;
    $id_b64 = trim($_POST['id_photo_base64'] ?? '');
    if ($id_b64) {
        $id_photo = saveBase64Image($id_b64, 'id_photo', $upload_dir);
        if (!$id_photo) $errors[] = 'Captured ID photo could not be saved';
    } else {
        $id_photo = saveUploadedFile('id_photo', 'id_photo', $upload_dir, $errors);
    }

    if (empty($errors)) {
        try {
            // addBorrower signature: (conn, first, last, address, contact, id_type, id_number, occupation, photo)
            // We store id_photo in a separate column — make sure to add it if needed
            $sql = "INSERT INTO borrowers
                        (first_name, last_name, address, contact, id_type, id_number, occupation, photo, id_photo)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
            executeQuery($conn, $sql,
                [$first_name, $last_name, $address, $contact, $id_type, $id_number, $occupation, $photo, $id_photo],
                "sssssssss"
            );
            header('Location: /cash_lending/borrowers.php?success=1');
            exit();
        } catch (Exception $e) {
            // Fallback: try without id_photo column if it doesn't exist yet
            try {
                addBorrower($conn, $first_name, $last_name, $address, $contact, $id_type, $id_number, $occupation, $photo);
                header('Location: /cash_lending/borrowers.php?success=1');
                exit();
            } catch (Exception $e2) {
                $errors[] = 'Error saving borrower: ' . $e2->getMessage();
            }
        }
    }
}

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">
                <!-- Live video -->
                <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()" id="snapBtn">
                            <i class="fas fa-circle"></i> Capture
                        </button>
                    </div>
                </div>
                <!-- Captured preview -->
                <div id="captureView" class="d-none">
                    <canvas id="captureCanvas" style="width:100%;border-radius:12px;max-height:300px;object-fit:cover;"></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>
                <!-- Error -->
                <div id="cameraError" class="d-none">
                    <i class="fas fa-video-slash fa-3x text-muted mb-3"></i>
                    <p class="text-muted mb-0">Camera not accessible.<br>Please allow camera permission or upload a file instead.</p>
                </div>
                <!-- Loading -->
                <div id="cameraLoading">
                    <div class="spinner-border text-primary my-4" role="status"></div>
                    <p class="text-muted">Starting camera…</p>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row mb-4">
    <div class="col-lg-8">
        <h3><i class="fas fa-user-plus"></i> Add New 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">
                <i class="fas fa-exclamation-circle"></i> Please correct the following:
                <ul class="mb-0 mt-2">
                    <?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" id="borrowerForm">
            <!-- Hidden base64 fields (filled by camera capture) -->
            <input type="hidden" name="photo_base64"    id="photo_base64">
            <input type="hidden" name="id_photo_base64" id="id_photo_base64">

            <!-- ── SECTION: Photos ─────────────────────────────────────────── -->
            <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;color:#374151;">
                            <i class="fas fa-user-circle text-primary me-1"></i> Borrower Photo
                        </div>
                        <img id="photoPreview"
                             src="https://ui-avatars.com/api/?name=New+Borrower&size=120&background=0d6efd&color=fff&rounded=true"
                             style="width:110px;height:110px;object-fit:cover;border-radius:50%;border:3px solid #0d6efd;margin-bottom:12px;"
                             alt="Borrower Photo">
                        <div id="photoLabel" class="text-muted mb-3" style="font-size:12px;">No photo selected</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 d-none" id="photoClearBtn" onclick="clearPhoto('photo')">
                                <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;color:#374151;">
                            <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;
                                    display:flex;align-items:center;justify-content:center;
                                    background:#fff;margin-bottom:12px;overflow:hidden;position:relative;">
                            <img id="idPhotoPreview" src="" alt="ID Preview"
                                 style="width:100%;height:100%;object-fit:cover;display:none;border-radius:8px;">
                            <span id="idPhotoPlaceholder" style="color:#9ca3af;font-size:12px;text-align:center;padding:8px;">
                                <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;">No ID photo selected</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 d-none" id="idPhotoClearBtn" onclick="clearPhoto('id_photo')">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- ── SECTION: Personal Info ──────────────────────────────────── -->
            <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($_POST['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($_POST['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($_POST['address'] ?? ''); ?></textarea>
            </div>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label fw-semibold">Contact Number <span class="text-danger">*</span></label>
                    <input type="tel" class="form-control" name="contact" placeholder="09XXXXXXXXX" required
                           value="<?php echo htmlspecialchars($_POST['contact'] ?? ''); ?>">
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label fw-semibold">Occupation</label>
                    <input type="text" class="form-control" name="occupation"
                           value="<?php echo htmlspecialchars($_POST['occupation'] ?? ''); ?>">
                </div>
            </div>

            <!-- ── SECTION: ID ─────────────────────────────────────────────── -->
            <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 ID Type --</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="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($_POST['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 Borrower
                </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>
// ── State ──────────────────────────────────────────────────────────────────
let stream       = null;
let currentFacing = 'user';   // 'user' = front, 'environment' = rear
let activeTarget = 'photo';   // which slot we're capturing for

// ── Open camera modal ──────────────────────────────────────────────────────
function openCamera(target) {
    activeTarget = target;
    const label = target === 'photo' ? 'Take Borrower Photo' : 'Capture ID Photo';
    document.getElementById('cameraModalTitle').innerHTML =
        `<i class="fas fa-camera me-2 text-primary"></i>${label}`;

    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');

    const modal = new bootstrap.Modal(document.getElementById('cameraModal'));
    modal.show();
    startCamera();
}

// ── Start camera stream ────────────────────────────────────────────────────
async function startCamera() {
    stopCamera();
    try {
        stream = await navigator.mediaDevices.getUserMedia({
            video: { facingMode: currentFacing, width: { ideal: 1280 }, height: { ideal: 720 } },
            audio: false
        });
        const video = document.getElementById('cameraStream');
        video.srcObject = stream;
        document.getElementById('cameraLoading').classList.add('d-none');
        document.getElementById('cameraView').classList.remove('d-none');
    } catch (err) {
        document.getElementById('cameraLoading').classList.add('d-none');
        document.getElementById('cameraError').classList.remove('d-none');
        console.warn('Camera error:', err);
    }
}

// ── Flip front/rear ────────────────────────────────────────────────────────
function flipCamera() {
    currentFacing = currentFacing === 'user' ? 'environment' : 'user';
    startCamera();
}

// ── Capture frame from video ───────────────────────────────────────────────
function capturePhoto() {
    const video  = document.getElementById('cameraStream');
    const canvas = document.getElementById('captureCanvas');
    canvas.width  = video.videoWidth  || 640;
    canvas.height = video.videoHeight || 480;
    canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);

    stopCamera();
    document.getElementById('cameraView').classList.add('d-none');
    document.getElementById('captureView').classList.remove('d-none');
}

// ── Retake ─────────────────────────────────────────────────────────────────
function retakePhoto() {
    document.getElementById('captureView').classList.add('d-none');
    document.getElementById('cameraLoading').classList.remove('d-none');
    startCamera();
}

// ── Use captured photo ─────────────────────────────────────────────────────
function usePhoto() {
    const canvas  = document.getElementById('captureCanvas');
    const dataURL = canvas.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').classList.remove('d-none');
        // Clear file input so base64 takes priority
        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').classList.remove('d-none');
        document.getElementById('id_photo').value = '';
    }

    bootstrap.Modal.getInstance(document.getElementById('cameraModal')).hide();
    stopCamera();
}

// ── Stop all camera tracks ─────────────────────────────────────────────────
function stopCamera() {
    if (stream) {
        stream.getTracks().forEach(t => t.stop());
        stream = null;
    }
}

// ── Handle file upload preview ─────────────────────────────────────────────
function handleFileSelect(input, target) {
    if (!input.files || !input.files[0]) return;
    const reader = new FileReader();
    reader.onload = function(e) {
        if (target === 'photo') {
            document.getElementById('photoPreview').src        = e.target.result;
            document.getElementById('photoLabel').textContent  = '📁 ' + input.files[0].name;
            document.getElementById('photoClearBtn').classList.remove('d-none');
            document.getElementById('photo_base64').value = ''; // clear camera data
        } 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').classList.remove('d-none');
            document.getElementById('id_photo_base64').value = '';
        }
    };
    reader.readAsDataURL(input.files[0]);
}

// ── Clear a photo slot ─────────────────────────────────────────────────────
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=New+Borrower&size=120&background=0d6efd&color=fff&rounded=true';
        document.getElementById('photoLabel').textContent = 'No photo selected';
        document.getElementById('photoClearBtn').classList.add('d-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 selected';
        document.getElementById('idPhotoClearBtn').classList.add('d-none');
    }
}

// Stop camera when modal closes via X or backdrop
document.getElementById('cameraModal')
    .addEventListener('hidden.bs.modal', stopCamera);
</script>

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