<?php
declare(strict_types=1);
$prefill_school_id = trim((string)($_GET['school_id'] ?? ''));

require_once __DIR__ . "/../config/db.php";
require_once __DIR__ . "/../config/auth.php";

require_login();
$u = current_user();
$uid = (int)($u['id'] ?? 0);
$role = (string)($u['role'] ?? 'REP');

// Get assigned districts, blocks, GPs for REP
$assigned_dist_blocks_gps = [];
if ($role !== 'ADMIN') {
    $st = $pdo->prepare("
        SELECT DISTINCT
            b.district_id,
            b.id AS block_id,
            g.id AS gp_id,
            d.name AS district_name,
            b.name AS block_name,
            g.name AS gp_name
        FROM gp_assignments a
        JOIN gps g ON g.id = a.gp_id
        JOIN blocks b ON b.id = g.block_id
        LEFT JOIN districts d ON d.id = b.district_id
        WHERE a.user_id = ? AND a.status = 'ACTIVE'
        ORDER BY d.name, b.name, g.name
    ");
    $st->execute([$uid]);
    $assigned_dist_blocks_gps = $st->fetchAll(PDO::FETCH_ASSOC);
}

$success = "";
$error = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = (string)($_POST['csrf'] ?? '');
    if (!csrf_validate($token)) {
        $error = "Invalid request.";
    } else {
        $visit_date = (string)($_POST['visit_date'] ?? '');
        $district_id = (string)($_POST['district_id'] ?? '');
        $block_id = (string)($_POST['block_id'] ?? '');
        $gp_id = (string)($_POST['gp_id'] ?? '');
        $school_id = (string)($_POST['school_id'] ?? '');

        $permission_status = (string)($_POST['permission_status'] ?? '');
        $authority_response = (string)($_POST['authority_response'] ?? '');
        $followup_required = (int)($_POST['followup_required'] ?? 0);
        $followup_date = (string)($_POST['followup_date'] ?? '');
        $remarks = trim((string)($_POST['remarks'] ?? ''));

        // Ear details fields
        $left_ear_status = (string)($_POST['left_ear_status'] ?? '');
        $right_ear_status = (string)($_POST['right_ear_status'] ?? '');
        $left_ear_remarks = trim((string)($_POST['left_ear_remarks'] ?? ''));
        $right_ear_remarks = trim((string)($_POST['right_ear_remarks'] ?? ''));
        $hearing_aid_required = (int)($_POST['hearing_aid_required'] ?? 0);
        $hearing_aid_remarks = trim((string)($_POST['hearing_aid_remarks'] ?? ''));
        $referral_required = (int)($_POST['referral_required'] ?? 0);
        $referral_remarks = trim((string)($_POST['referral_remarks'] ?? ''));

        if ($visit_date === '' || $district_id==='' || $block_id==='' || $school_id==='' || $permission_status==='') {
            $error = "Please fill all required fields (District, Block, School, Date, Permission).";
        } else {
            // Security: REP can only save to their assigned blocks or GPs
            if ($role !== 'ADMIN') {
                if ($gp_id !== '') {
                    $st = $pdo->prepare("SELECT 1 FROM gp_assignments WHERE user_id=? AND gp_id=? AND status='ACTIVE' LIMIT 1");
                    $st->execute([$uid, $gp_id]);
                    if (!$st->fetchColumn()) {
                        $error = "You are not assigned to this GP.";
                    }
                } else {
                    $st = $pdo->prepare("SELECT 1 FROM gp_assignments WHERE user_id=? AND block_id=? AND status='ACTIVE' LIMIT 1");
                    $st->execute([$uid, $block_id]);
                    if (!$st->fetchColumn()) {
                        $error = "You are not assigned to any GP in this block.";
                    }
                }
            }

            if ($error === '') {
                try {
                    $pdo->beginTransaction();

                    $followup_date_db = null;
                    if ($followup_required === 1 && $followup_date !== '') {
                        $followup_date_db = $followup_date;
                    }

                    $gp_id_db = ($gp_id !== '') ? $gp_id : null;

                    // Insert into visits table
                    $st = $pdo->prepare("
                        INSERT INTO visits
                        (visit_date, block_id, gp_id, school_id, permission_status, authority_response, followup_required, followup_date, remarks, visited_by)
                        VALUES (?,?,?,?,?,?,?,?,?,?)
                    ");
                    $st->execute([
                        $visit_date, $block_id, $gp_id_db, $school_id,
                        $permission_status,
                        $authority_response !== '' ? $authority_response : null,
                        $followup_required,
                        $followup_date_db,
                        $remarks !== '' ? $remarks : null,
                        $uid
                    ]);

                    $visit_id = $pdo->lastInsertId();

                    // Insert into visit_ear_details table
                    if ($left_ear_status !== '' || $right_ear_status !== '' || $hearing_aid_required === 1 || $referral_required === 1) {
                        $st = $pdo->prepare("
                            INSERT INTO visit_ear_details
                            (visit_id, left_ear_status, right_ear_status, left_ear_remarks, right_ear_remarks, hearing_aid_required, hearing_aid_remarks, referral_required, referral_remarks)
                            VALUES (?,?,?,?,?,?,?,?,?)
                        ");
                        $st->execute([
                            $visit_id,
                            $left_ear_status !== '' ? $left_ear_status : null,
                            $right_ear_status !== '' ? $right_ear_status : null,
                            $left_ear_remarks !== '' ? $left_ear_remarks : null,
                            $right_ear_remarks !== '' ? $right_ear_remarks : null,
                            $hearing_aid_required,
                            $hearing_aid_remarks !== '' ? $hearing_aid_remarks : null,
                            $referral_required,
                            $referral_remarks !== '' ? $referral_remarks : null
                        ]);
                    }

                    $pdo->commit();
                    $success = "Visit saved successfully.";

                } catch (Exception $e) {
                    $pdo->rollBack();
                    $error = "Error saving visit: " . $e->getMessage();
                }
            }
        }
    }
}

$page_title = "Add Visit";
require_once __DIR__ . "/partials/header.php";
?>

<div class="row justify-content-center">
    <div class="col-12 col-lg-10">
        <div class="card card-soft shadow-soft p-3 p-md-4">

            <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-2 mb-3">
                <div>
                    <h5 class="mb-0">Add Visit</h5>
                    <div class="text-muted small">District → Block → GP → School</div>
                </div>
                <a class="btn btn-outline-dark btn-sm" href="/school-crm/public/dashboard.php">Back</a>
            </div>

            <?php if ($success): ?>
                <div class="alert alert-success py-2"><?= htmlspecialchars($success) ?></div>
            <?php endif; ?>
            <?php if ($error): ?>
                <div class="alert alert-danger py-2"><?= htmlspecialchars($error) ?></div>
            <?php endif; ?>

            <form method="post" class="mt-2" id="visitForm">
                <input type="hidden" name="csrf" value="<?= htmlspecialchars(csrf_token()) ?>">

                <!-- Basic Visit Information -->
                <div class="row g-3 mb-4">
                    <div class="col-12">
                        <h6 class="border-bottom pb-2">Basic Information</h6>
                    </div>

                    <div class="col-12 col-md-4">
                        <label class="form-label">Visit Date <span class="text-danger">*</span></label>
                        <input type="date" class="form-control" name="visit_date" value="<?= htmlspecialchars(date('Y-m-d')) ?>" required>
                    </div>

                    <div class="col-12 col-md-4">
                        <label class="form-label">District <span class="text-danger">*</span></label>
                        <select class="form-select" id="district" name="district_id" required>
                            <option value="">Select District</option>
                        </select>
                    </div>

                    <div class="col-12 col-md-4">
                        <label class="form-label">Block <span class="text-danger">*</span></label>
                        <select class="form-select" id="block" name="block_id" required disabled>
                            <option value="">Select Block</option>
                        </select>
                    </div>

                    <div class="col-12 col-md-6">
                        <label class="form-label">GP <span class="text-muted small">(Optional)</span></label>
                        <select class="form-select" id="gp" name="gp_id" disabled>
                            <option value="">Select GP or Skip</option>
                        </select>
                    </div>

                    <div class="col-12 col-md-6">
                        <label class="form-label">School <span class="text-danger">*</span></label>
                        <select class="form-select" id="school" name="school_id" required disabled>
                            <option value="">Select School</option>
                        </select>
                    </div>

                    <div class="col-12">
                        <div class="card card-soft p-3">
                            <div class="fw-semibold mb-1">Selected School Details</div>
                            <div class="text-muted small" id="schoolDetails">Select a school to view details.</div>
                            <div id="schoolContactWrap" style="display:none; margin-top:12px;">
                                <div class="row g-2">
                                    <div class="col-md-6">
                                        <label class="form-label">School Contact No</label>
                                        <input type="text" class="form-control" id="schoolContact" readonly>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">WhatsApp No</label>
                                        <input type="text" class="form-control" id="schoolWhatsapp" readonly>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Visit Response Information -->
                <div class="row g-3 mb-4">
                    <div class="col-12">
                        <h6 class="border-bottom pb-2">Visit Response</h6>
                    </div>

                    <div class="col-12 col-md-4">
                        <label class="form-label">Permission Status <span class="text-danger">*</span></label>
                        <select class="form-select" name="permission_status" required>
                            <option value="">Select</option>
                            <option value="GRANTED">Granted</option>
                            <option value="PENDING">Pending</option>
                            <option value="DENIED">Denied</option>
                        </select>
                    </div>

                    <div class="col-12 col-md-4">
                        <label class="form-label">Authority Response</label>
                        <select class="form-select" name="authority_response">
                            <option value="">(Optional)</option>
                            <option value="VERY_POSITIVE">Very Positive</option>
                            <option value="NEED_INFO">Need Info</option>
                            <option value="CONTACT_LATER">Contact Later</option>
                            <option value="NOT_INTERESTED">Not Interested</option>
                        </select>
                    </div>

                    <div class="col-12 col-md-4">
                        <label class="form-label">Follow-up Required?</label>
                        <select class="form-select" id="followup_required" name="followup_required">
                            <option value="0">No</option>
                            <option value="1">Yes</option>
                        </select>
                    </div>

                    <div class="col-12 col-md-4" id="followupDateWrap" style="display:none;">
                        <label class="form-label">Follow-up Date</label>
                        <input type="date" class="form-control" name="followup_date">
                    </div>

                    <div class="col-12">
                        <label class="form-label">General Remarks</label>
                        <textarea class="form-control" name="remarks" rows="2" placeholder="Write notes..."></textarea>
                    </div>
                </div>

                <!-- Ear Examination Details -->
                <div class="row g-3 mb-4">
                    <div class="col-12">
                        <h6 class="border-bottom pb-2">Ear Examination Details</h6>
                    </div>

                    <div class="col-12 col-md-6">
                        <label class="form-label">Left Ear Status</label>
                        <select class="form-select" name="left_ear_status">
                            <option value="">Select Status</option>
                            <option value="NORMAL">Normal</option>
                            <option value="WAX">Wax</option>
                            <option value="INFECTION">Infection</option>
                            <option value="PERFORATION">Perforation</option>
                            <option value="OTHER">Other</option>
                        </select>
                    </div>

                    <div class="col-12 col-md-6">
                        <label class="form-label">Right Ear Status</label>
                        <select class="form-select" name="right_ear_status">
                            <option value="">Select Status</option>
                            <option value="NORMAL">Normal</option>
                            <option value="WAX">Wax</option>
                            <option value="INFECTION">Infection</option>
                            <option value="PERFORATION">Perforation</option>
                            <option value="OTHER">Other</option>
                        </select>
                    </div>

                    <div class="col-12 col-md-6">
                        <label class="form-label">Left Ear Remarks</label>
                        <textarea class="form-control" name="left_ear_remarks" rows="2" placeholder="Details about left ear..."></textarea>
                    </div>

                    <div class="col-12 col-md-6">
                        <label class="form-label">Right Ear Remarks</label>
                        <textarea class="form-control" name="right_ear_remarks" rows="2" placeholder="Details about right ear..."></textarea>
                    </div>
                </div>

                <!-- Hearing Aid & Referral Information -->
                <div class="row g-3 mb-4">
                    <div class="col-12">
                        <h6 class="border-bottom pb-2">Hearing Aid & Referral</h6>
                    </div>

                    <div class="col-12 col-md-4">
                        <label class="form-label">Hearing Aid Required?</label>
                        <select class="form-select" name="hearing_aid_required" id="hearing_aid_required">
                            <option value="0">No</option>
                            <option value="1">Yes</option>
                        </select>
                    </div>

                    <div class="col-12 col-md-8" id="hearingAidRemarksWrap">
                        <label class="form-label">Hearing Aid Remarks</label>
                        <textarea class="form-control" name="hearing_aid_remarks" rows="2" placeholder="Hearing aid details..."></textarea>
                    </div>

                    <div class="col-12 col-md-4">
                        <label class="form-label">Referral Required?</label>
                        <select class="form-select" name="referral_required" id="referral_required">
                            <option value="0">No</option>
                            <option value="1">Yes</option>
                        </select>
                    </div>

                    <div class="col-12 col-md-8" id="referralRemarksWrap">
                        <label class="form-label">Referral Remarks</label>
                        <textarea class="form-control" name="referral_remarks" rows="2" placeholder="Referral details..."></textarea>
                    </div>
                </div>

                <div class="col-12 d-grid d-md-flex justify-content-md-end">
                    <button class="btn btn-dark px-4" type="submit">Save Visit</button>
                </div>
            </form>

        </div>
    </div>
</div>

<script>
const $district = document.getElementById('district');
const $block    = document.getElementById('block');
const $gp       = document.getElementById('gp');
const $school   = document.getElementById('school');
const $details  = document.getElementById('schoolDetails');

function setOptions(selectEl, rows, placeholder) {
    selectEl.innerHTML = '';
    const opt0 = document.createElement('option');
    opt0.value = '';
    opt0.textContent = placeholder;
    selectEl.appendChild(opt0);
    rows.forEach(r => {
        const o = document.createElement('option');
        o.value = r.id;
        o.textContent = r.name;
        selectEl.appendChild(o);
    });
}

function disableAndReset(selectEl, placeholder) {
    selectEl.disabled = true;
    setOptions(selectEl, [], placeholder);
}

async function loadJSON(url) {
    const res = await fetch(url, {credentials:'same-origin'});
    if (!res.ok) return [];
    return await res.json();
}

// User role and assignments data (passed from PHP)
const userRole = "<?= htmlspecialchars($role) ?>";
const assignedLocations = <?= json_encode($assigned_dist_blocks_gps) ?>;

// Helper: Get unique assigned districts for REP
function getAssignedDistricts() {
    const districts = [];
    const seen = new Set();
    assignedLocations.forEach(item => {
        if (!seen.has(item.district_id)) {
            seen.add(item.district_id);
            districts.push({id: item.district_id, name: item.district_name || item.district_id});
        }
    });
    return districts;
}

// Helper: Get blocks for a district (only assigned for REP)
function getBlocksForDistrict(districtId) {
    const blocks = [];
    const seen = new Set();
    assignedLocations.forEach(item => {
        if (item.district_id === districtId && !seen.has(item.block_id)) {
            seen.add(item.block_id);
            blocks.push({id: item.block_id, name: item.block_name});
        }
    });
    return blocks;
}

// Helper: Get GPs for a block (only assigned for REP)
function getGPsForBlock(blockId) {
    const gps = [];
    const seen = new Set();
    assignedLocations.forEach(item => {
        if (item.block_id === blockId && !seen.has(item.gp_id)) {
            seen.add(item.gp_id);
            gps.push({id: item.gp_id, name: item.gp_name});
        }
    });
    return gps;
}

// Load districts on page load
(async function init(){
    let districts;
    if (userRole === 'ADMIN') {
        districts = await loadJSON('/school-crm/api/districts.php');
    } else {
        districts = getAssignedDistricts();
    }
    setOptions($district, districts, 'Select District');
    
    const prefillSchoolId = "<?= htmlspecialchars($prefill_school_id) ?>";
    if (prefillSchoolId) {
        await prefillSchool(prefillSchoolId);
    }
})();

// District change -> load blocks
$district.addEventListener('change', async () => {
    $details.textContent = "Select a school to view details.";
    disableAndReset($block, 'Select Block');
    disableAndReset($gp, 'Select GP');
    disableAndReset($school, 'Select School');

    const did = $district.value;
    if (!did) return;

    let blocks;
    if (userRole === 'ADMIN') {
        blocks = await loadJSON('/school-crm/api/blocks.php?district_id=' + encodeURIComponent(did));
    } else {
        blocks = getBlocksForDistrict(did);
    }
    setOptions($block, blocks, 'Select Block');
    $block.disabled = false;
});

// Block change -> load gps AND schools
$block.addEventListener('change', async () => {
    $details.textContent = "Select a school to view details.";
    disableAndReset($gp, 'Select GP');
    disableAndReset($school, 'Select School');

    const bid = $block.value;
    if (!bid) return;

    let gps;
    if (userRole === 'ADMIN') {
        gps = await loadJSON('/school-crm/api/gps.php?block_id=' + encodeURIComponent(bid));
    } else {
        gps = getGPsForBlock(bid);
    }
    setOptions($gp, gps, 'Select GP (Optional)');
    $gp.disabled = false;

    const schools = await loadJSON('/school-crm/api/schools.php?block_id=' + encodeURIComponent(bid));
    setOptions($school, schools, 'Select School');
    $school.disabled = false;
});

// GP change -> filter schools
$gp.addEventListener('change', async () => {
    $details.textContent = "Select a school to view details.";
    
    const gid = $gp.value;
    const bid = $block.value;
    
    if (!bid) return;

    if (gid) {
        const schools = await loadJSON('/school-crm/api/schools.php?gp_id=' + encodeURIComponent(gid));
        setOptions($school, schools, 'Select School');
        $school.disabled = false;
    } else {
        const schools = await loadJSON('/school-crm/api/schools.php?block_id=' + encodeURIComponent(bid));
        setOptions($school, schools, 'Select School');
        $school.disabled = false;
    }
});

// School change -> details
$school.addEventListener('change', async () => {
    const sid = $school.value;
    const $schoolContactWrap = document.getElementById('schoolContactWrap');
    const $schoolContact = document.getElementById('schoolContact');
    const $schoolWhatsapp = document.getElementById('schoolWhatsapp');
    
    if (!sid) {
        $details.textContent = "Select a school to view details.";
        if ($schoolContactWrap) $schoolContactWrap.style.display = 'none';
        if ($schoolContact) $schoolContact.value = '';
        if ($schoolWhatsapp) $schoolWhatsapp.value = '';
        return;
    }

    const info = await loadJSON('/school-crm/api/school_details.php?school_id=' + encodeURIComponent(sid));
    if (!info || info.error) {
        $details.textContent = "No details found.";
        if ($schoolContactWrap) $schoolContactWrap.style.display = 'none';
        if ($schoolContact) $schoolContact.value = '';
        if ($schoolWhatsapp) $schoolWhatsapp.value = '';
        return;
    }

    $details.innerHTML =
        `<div><b>School:</b> ${escapeHtml(info.name)}</div>` +
        `<div><b>District:</b> ${escapeHtml(info.district_name ?? '')}</div>` +
        `<div><b>Block:</b> ${escapeHtml(info.block_name ?? '')}</div>` +
        `<div><b>GP:</b> ${escapeHtml(info.gp_name ?? '')}</div>` +
        `<div><b>Address:</b> ${escapeHtml(info.address ?? '')}</div>` +
        `<div><b>Category:</b> ${escapeHtml(info.category ?? '')}</div>`;
    
    if ($schoolContactWrap) $schoolContactWrap.style.display = 'block';
    if ($schoolContact) $schoolContact.value = info.contact_no || '';
    if ($schoolWhatsapp) $schoolWhatsapp.value = info.whatsapp_no || '';
});

function escapeHtml(str){
    if (str === null || str === undefined) return '';
    return String(str).replace(/[&<>"']/g, s => ({
        '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'
    }[s]));
}

// Followup show/hide
document.getElementById('followup_required').addEventListener('change', (e)=>{
    document.getElementById('followupDateWrap').style.display = (e.target.value === '1') ? 'block' : 'none';
});

// Prefill school function
async function prefillSchool(schoolId) {
    if (!schoolId) return;

    try {
        console.log('Starting prefill for school ID:', schoolId);
        
        const info = await loadJSON('/school-crm/api/school_details.php?school_id=' + encodeURIComponent(schoolId));
        console.log('School details received:', info);
        
        if (!info || !info.district_id) {
            console.error('School details not found or missing district_id');
            return;
        }

        function waitForOptions(selectElement, timeout = 5000) {
            return new Promise((resolve) => {
                const startTime = Date.now();
                const checkInterval = setInterval(() => {
                    const hasOptions = selectElement.options.length > 1;
                    if (hasOptions || Date.now() - startTime > timeout) {
                        clearInterval(checkInterval);
                        resolve(hasOptions);
                    }
                }, 100);
            });
        }

        function waitForValue(selectElement, value, timeout = 5000) {
            return new Promise((resolve) => {
                const startTime = Date.now();
                const checkInterval = setInterval(() => {
                    const options = Array.from(selectElement.options).map(opt => opt.value);
                    if (options.includes(value) || Date.now() - startTime > timeout) {
                        clearInterval(checkInterval);
                        resolve(options.includes(value));
                    }
                }, 100);
            });
        }

        function setSelectValue(select, value, shouldTriggerChange = true) {
            if (value && select.querySelector(`option[value="${value}"]`)) {
                select.value = value;
                if (shouldTriggerChange) {
                    select.dispatchEvent(new Event('change', { bubbles: true }));
                }
                return true;
            }
            return false;
        }

        await waitForOptions($district);
        if (setSelectValue($district, info.district_id)) {
            
            await waitForOptions($block);
            await waitForValue($block, info.block_id);
            
            if (setSelectValue($block, info.block_id)) {
                
                await Promise.all([
                    waitForOptions($gp),
                    waitForOptions($school)
                ]);
                
                if (info.gp_id) {
                    await waitForValue($gp, info.gp_id);
                    setSelectValue($gp, info.gp_id);
                }
                
                await waitForValue($school, schoolId);
                setSelectValue($school, schoolId);
                
                console.log('School prefill complete!');
            }
        }
    } catch (error) {
        console.error('Error pre-filling school:', error);
    }
}
</script>

<?php require_once __DIR__ . "/partials/footer.php"; ?>