<?php
// public/rep/school_add.php
declare(strict_types=1);

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

require_rep();

$u = current_user();
$uid = (int)($u['id'] ?? 0);
$rep_name = (string)($u['name'] ?? '');

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

/** helpers */
function fetchAll(PDO $pdo, string $sql, array $params = []): array {
    $st = $pdo->prepare($sql);
    $st->execute($params);
    return $st->fetchAll(PDO::FETCH_ASSOC);
}

function post_str(string $k): string {
    return trim((string)($_POST[$k] ?? ''));
}

// Get assigned districts for this rep (based on gp_assignments)
$assigned_districts = fetchAll($pdo, "
    SELECT DISTINCT d.id, d.name
    FROM gp_assignments a
    JOIN gps g ON g.id = a.gp_id
    JOIN blocks b ON b.id = g.block_id
    JOIN districts d ON d.id = b.district_id
    WHERE a.user_id = ? AND a.status = 'ACTIVE'
    ORDER BY d.name ASC
", [$uid]);

/**
 * CREATE School
 */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'create') {
    if (!csrf_validate($_POST['csrf'] ?? '')) {
        $error = "Invalid request.";
    } else {
        $school_id = strtoupper(post_str('school_id'));   // Generate or use manual ID
        $gp_id     = strtoupper(post_str('gp_id'));
        $name      = post_str('name');
        $address   = post_str('address');
        $category  = post_str('category');
        $contact_no = post_str('contact_no');
        $whatsapp_no = post_str('whatsapp_no');

        if ($school_id === '' || $gp_id === '' || $name === '') {
            $error = "School ID, GP and School Name are required.";
        } else {
            // Verify that the selected GP is actually assigned to this rep
            $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 can only add schools to your assigned GPs.";
            } else {
                try {
                    $st = $pdo->prepare("
                        INSERT INTO schools (id, gp_id, name, address, category, contact_no, whatsapp_no, created_by)
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                    ");
                    $st->execute([
                        $school_id,
                        $gp_id,
                        $name,
                        $address !== '' ? $address : null,
                        $category !== '' ? $category : null,
                        $contact_no !== '' ? $contact_no : null,
                        $whatsapp_no !== '' ? $whatsapp_no : null,
                        $uid // <-- Add this
                    ]);
                    $success = "School added successfully.";
                    // Clear form
                    $_POST = [];
                } catch (Throwable $e) {
                    if ($e->getCode() == 23000) { // Duplicate entry
                        $error = "School ID already exists. Please use a different ID.";
                    } else {
                        $error = "Failed to add school. Please try again.";
                        error_log("School add error: " . $e->getMessage());
                    }
                }
            }
        }
    }
}

/**
 * Get assigned GPs for dropdowns (for the cascade)
 */
$assigned_blocks = [];
$assigned_gps = [];

// If district selected via GET (for initial load)
$selected_district = strtoupper(trim((string)($_GET['district_id'] ?? '')));
$selected_block = strtoupper(trim((string)($_GET['block_id'] ?? '')));

if ($selected_district) {
    // Verify this district is in rep's assignments
    $st = $pdo->prepare("
        SELECT 1 FROM gp_assignments a
        JOIN gps g ON g.id = a.gp_id
        JOIN blocks b ON b.id = g.block_id
        WHERE a.user_id = ? AND a.status = 'ACTIVE' AND b.district_id = ?
        LIMIT 1
    ");
    $st->execute([$uid, $selected_district]);
    if ($st->fetchColumn()) {
        $assigned_blocks = fetchAll($pdo, "
            SELECT DISTINCT b.id, b.name
            FROM gp_assignments a
            JOIN gps g ON g.id = a.gp_id
            JOIN blocks b ON b.id = g.block_id
            WHERE a.user_id = ? AND a.status = 'ACTIVE' AND b.district_id = ?
            ORDER BY b.name ASC
        ", [$uid, $selected_district]);
    }
}

if ($selected_block) {
    // Verify this block is in rep's assignments
    $st = $pdo->prepare("
        SELECT 1 FROM gp_assignments a
        JOIN gps g ON g.id = a.gp_id
        WHERE a.user_id = ? AND a.status = 'ACTIVE' AND g.block_id = ?
        LIMIT 1
    ");
    $st->execute([$uid, $selected_block]);
    if ($st->fetchColumn()) {
        $assigned_gps = fetchAll($pdo, "
            SELECT DISTINCT g.id, g.name
            FROM gp_assignments a
            JOIN gps g ON g.id = a.gp_id
            WHERE a.user_id = ? AND a.status = 'ACTIVE' AND g.block_id = ?
            ORDER BY g.name ASC
        ", [$uid, $selected_block]);
    }
}

// Generate a suggested school ID (optional)
$suggested_id = "SCH-" . date('Y') . "-" . strtoupper(substr(uniqid(), -6));

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

<style>
:root {
    --primary: #4361ee;
    --success: #06d6a0;
    --warning: #ffb703;
    --danger: #ef476f;
    --dark: #073b4c;
    --info: #17a2b8;
    --purple: #6f42c1;
    --orange: #fd7e14;
    --light: #f8f9fa;
    --gray: #6c757d;
}

body {
    background: #f5f7fa;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
}

.dashboard-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 16px;
}

/* Welcome Section */
.welcome-section {
    background: linear-gradient(135deg, var(--primary), #3a0ca3);
    color: white;
    border-radius: 24px;
    padding: 24px;
    margin-bottom: 24px;
    box-shadow: 0 10px 30px rgba(67, 97, 238, 0.2);
}

.welcome-title {
    font-size: 1.8rem;
    font-weight: 700;
    margin-bottom: 8px;
}

.welcome-date {
    display: flex;
    align-items: center;
    gap: 20px;
    flex-wrap: wrap;
    opacity: 0.9;
    font-size: 0.95rem;
}

.welcome-date i {
    margin-right: 6px;
}

/* Form Card */
.form-card {
    background: white;
    border-radius: 24px;
    padding: 30px;
    border: 1px solid #e9ecef;
    box-shadow: 0 4px 12px rgba(0,0,0,0.03);
    margin-bottom: 24px;
}

.form-header {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 24px;
}

.form-header i {
    font-size: 2rem;
    color: var(--primary);
    background: rgba(67, 97, 238, 0.1);
    padding: 12px;
    border-radius: 16px;
}

.form-header h2 {
    margin: 0;
    font-size: 1.6rem;
    font-weight: 600;
    color: var(--dark);
}

.form-header p {
    margin: 4px 0 0;
    color: var(--gray);
    font-size: 0.9rem;
}

.form-label {
    font-weight: 500;
    color: var(--dark);
    margin-bottom: 6px;
    display: block;
}

.form-control, .form-select {
    width: 100%;
    padding: 12px 16px;
    border: 1px solid #e9ecef;
    border-radius: 12px;
    font-size: 0.95rem;
    transition: all 0.2s;
    background: white;
}

.form-control:focus, .form-select:focus {
    outline: none;
    border-color: var(--primary);
    box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.1);
}

.form-text {
    font-size: 0.8rem;
    color: var(--gray);
    margin-top: 4px;
}

.form-row {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
}

.btn-submit {
    background: linear-gradient(135deg, var(--primary), #3a0ca3);
    color: white;
    border: none;
    padding: 14px 32px;
    border-radius: 40px;
    font-size: 1rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
    display: inline-flex;
    align-items: center;
    gap: 8px;
}

.btn-submit:hover {
    transform: translateY(-2px);
    box-shadow: 0 12px 24px rgba(67, 97, 238, 0.3);
}

.btn-submit i {
    font-size: 1.2rem;
}

.btn-secondary {
    background: white;
    color: var(--dark);
    border: 1px solid #e9ecef;
    padding: 14px 32px;
    border-radius: 40px;
    font-size: 1rem;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 8px;
}

.btn-secondary:hover {
    background: var(--light);
}

.alert {
    padding: 16px 20px;
    border-radius: 16px;
    margin-bottom: 24px;
}

.alert-success {
    background: rgba(6, 214, 160, 0.1);
    color: var(--success);
    border: 1px solid rgba(6, 214, 160, 0.2);
}

.alert-danger {
    background: rgba(239, 71, 111, 0.1);
    color: var(--danger);
    border: 1px solid rgba(239, 71, 111, 0.2);
}

.alert-warning {
    background: rgba(255, 183, 3, 0.1);
    color: var(--warning);
    border: 1px solid rgba(255, 183, 3, 0.2);
}

.info-box {
    background: var(--light);
    border-radius: 16px;
    padding: 16px 20px;
    margin-bottom: 24px;
    display: flex;
    align-items: center;
    gap: 12px;
    border-left: 4px solid var(--info);
}

.info-box i {
    font-size: 1.5rem;
    color: var(--info);
}

.info-box p {
    margin: 0;
    color: var(--dark);
    font-size: 0.95rem;
}

.required::after {
    content: " *";
    color: var(--danger);
    font-weight: bold;
}

/* Quick Actions */
.quick-actions {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
    margin-bottom: 24px;
}

.quick-action {
    background: white;
    border: 1px solid #e9ecef;
    border-radius: 40px;
    padding: 10px 20px;
    text-decoration: none;
    color: var(--dark);
    font-size: 0.9rem;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    transition: all 0.2s;
}

.quick-action:hover {
    background: var(--primary);
    color: white;
    border-color: var(--primary);
}

.quick-action i {
    font-size: 1.1rem;
}

/* Mobile Responsive */
@media (max-width: 768px) {
    .dashboard-container {
        padding: 12px;
    }
    
    .welcome-section {
        padding: 20px;
    }
    
    .welcome-title {
        font-size: 1.4rem;
    }
    
    .form-card {
        padding: 20px;
    }
    
    .form-header h2 {
        font-size: 1.4rem;
    }
    
    .form-row {
        grid-template-columns: 1fr;
        gap: 16px;
    }
    
    .btn-submit, .btn-secondary {
        width: 100%;
        justify-content: center;
    }
    
    .quick-actions {
        justify-content: center;
    }
}
</style>

<div class="dashboard-container">
    <!-- Welcome Section -->
    <div class="welcome-section">
        <div class="welcome-title">
            <i class="bi bi-building-add"></i> Add New School
        </div>
        <div class="welcome-date">
            <span><i class="bi bi-person"></i> <?= htmlspecialchars($rep_name) ?></span>
            <span><i class="bi bi-calendar"></i> <?= date('l, d F Y') ?></span>
            <span><i class="bi bi-geo-alt"></i> <?= count($assigned_districts) ?> Districts Assigned</span>
        </div>
    </div>

    <!-- Quick Actions -->
    <div class="quick-actions">
        <a href="/school-crm/public/dashboard.php" class="quick-action">
            <i class="bi bi-house"></i> Dashboard
        </a>
        <a href="/school-crm/public/rep/my_schools.php" class="quick-action">
            <i class="bi bi-building"></i> My Schools
        </a>
        <a href="/school-crm/public/visit_add.php" class="quick-action">
            <i class="bi bi-plus-circle"></i> Add Visit
        </a>
        <a href="/school-crm/public/visits.php" class="quick-action">
            <i class="bi bi-clock-history"></i> History
        </a>
    </div>

    <?php if ($success): ?>
        <div class="alert alert-success">
            <i class="bi bi-check-circle-fill me-2"></i>
            <?= htmlspecialchars($success) ?>
        </div>
    <?php endif; ?>
    
    <?php if ($error): ?>
        <div class="alert alert-danger">
            <i class="bi bi-exclamation-triangle-fill me-2"></i>
            <?= htmlspecialchars($error) ?>
        </div>
    <?php endif; ?>

    <!-- Info Box -->
    <div class="info-box">
        <i class="bi bi-info-circle"></i>
        <p>
            <strong>Important:</strong> You can only add schools to Gram Panchayats (GPs) that are assigned to you. 
            The school ID should be unique. If you don't have a specific ID, you can use the suggested format.
        </p>
    </div>

    <!-- Add School Form -->
    <div class="form-card">
        <div class="form-header">
            <i class="bi bi-building"></i>
            <div>
                <h2>School Details</h2>
                <p>Fill in the information below to add a new school</p>
            </div>
        </div>

        <form method="post" id="addSchoolForm">
            <input type="hidden" name="csrf" value="<?= htmlspecialchars(csrf_token()) ?>">
            <input type="hidden" name="action" value="create">

            <!-- District Selection (for navigation only) -->
            <div class="form-row">
                <div>
                    <label class="form-label">District</label>
                    <select class="form-select" id="districtSel">
                        <option value="">-- Select District --</option>
                        <?php foreach ($assigned_districts as $d): ?>
                            <option value="<?= htmlspecialchars($d['id']) ?>" 
                                <?= ($selected_district === $d['id']) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($d['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <div class="form-text">Select district to load blocks</div>
                </div>

                <div>
                    <label class="form-label">Block</label>
                    <select class="form-select" id="blockSel" <?= empty($assigned_blocks) ? 'disabled' : '' ?>>
                        <option value="">-- Select Block --</option>
                        <?php foreach ($assigned_blocks as $b): ?>
                            <option value="<?= htmlspecialchars($b['id']) ?>" 
                                <?= ($selected_block === $b['id']) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($b['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <div class="form-text">Select block to load GPs</div>
                </div>
            </div>

            <!-- GP Selection (actual form field) -->
            <div class="form-row">
                <div>
                    <label class="form-label required">Gram Panchayat (GP)</label>
                    <select class="form-select" name="gp_id" id="gpSel" required <?= empty($assigned_gps) ? 'disabled' : '' ?>>
                        <option value="">-- Select GP --</option>
                        <?php foreach ($assigned_gps as $g): ?>
                            <option value="<?= htmlspecialchars($g['id']) ?>">
                                <?= htmlspecialchars($g['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <div class="form-text">Select the GP where this school belongs</div>
                </div>

                <div>
                    <label class="form-label required">School ID</label>
                    <input class="form-control" name="school_id" 
                           value="<?= htmlspecialchars($_POST['school_id'] ?? $suggested_id) ?>" 
                           placeholder="e.g., SCH-2024-001" required>
                    <div class="form-text">Unique identifier for the school</div>
                </div>
            </div>

            <div class="form-row">
                <div>
                    <label class="form-label required">School Name</label>
                    <input class="form-control" name="name" 
                           value="<?= htmlspecialchars($_POST['name'] ?? '') ?>" 
                           placeholder="Full school name" required>
                </div>

                <div>
                    <label class="form-label">Category</label>
                    <input class="form-control" name="category" 
                           value="<?= htmlspecialchars($_POST['category'] ?? '') ?>" 
                           placeholder="e.g., Primary, High School, etc.">
                </div>
            </div>

            <div class="form-row">
                <div>
                    <label class="form-label">Address</label>
                    <textarea class="form-control" name="address" rows="2" 
                              placeholder="Full address"><?= htmlspecialchars($_POST['address'] ?? '') ?></textarea>
                </div>
            </div>

            <div class="form-row">
                <div>
                    <label class="form-label">Contact Number</label>
                    <input class="form-control" name="contact_no" 
                           value="<?= htmlspecialchars($_POST['contact_no'] ?? '') ?>" 
                           placeholder="Phone number">
                </div>

                <div>
                    <label class="form-label">WhatsApp Number</label>
                    <input class="form-control" name="whatsapp_no" 
                           value="<?= htmlspecialchars($_POST['whatsapp_no'] ?? '') ?>" 
                           placeholder="WhatsApp number">
                </div>
            </div>

            <div class="d-flex justify-content-between align-items-center mt-4">
                <a href="/school-crm/public/rep/my_schools.php" class="btn-secondary">
                    <i class="bi bi-arrow-left"></i> Cancel
                </a>
                <button type="submit" class="btn-submit">
                    <i class="bi bi-check-circle"></i> Add School
                </button>
            </div>
        </form>
    </div>

    <!-- Tips Card -->
    <div class="form-card" style="background: var(--light);">
        <div class="form-header">
            <i class="bi bi-lightbulb" style="color: var(--warning);"></i>
            <div>
                <h5 style="margin: 0;">Tips for Adding Schools</h5>
                <p class="text-muted" style="margin: 4px 0 0;">Follow these guidelines</p>
            </div>
        </div>
        
        <div class="row g-3">
            <div class="col-12 col-md-4">
                <div class="d-flex gap-2">
                    <i class="bi bi-1-circle-fill text-primary"></i>
                    <div>
                        <strong>Select Location First</strong>
                        <p class="small text-muted">Always select District → Block → GP in order</p>
                    </div>
                </div>
            </div>
            
            <div class="col-12 col-md-4">
                <div class="d-flex gap-2">
                    <i class="bi bi-2-circle-fill text-primary"></i>
                    <div>
                        <strong>Unique School ID</strong>
                        <p class="small text-muted">Use a consistent format like SCH-YYYY-NNN</p>
                    </div>
                </div>
            </div>
            
            <div class="col-12 col-md-4">
                <div class="d-flex gap-2">
                    <i class="bi bi-3-circle-fill text-primary"></i>
                    <div>
                        <strong>Complete Information</strong>
                        <p class="small text-muted">Add contact details for future follow-ups</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
async function loadJSON(url) {
    try {
        const res = await fetch(url, { credentials: 'same-origin' });
        if (!res.ok) return [];
        return await res.json();
    } catch (e) {
        console.error('Fetch error:', e);
        return [];
    }
}

function setOptions(selectEl, rows, placeholder, selectedValue = '') {
    selectEl.innerHTML = '';
    
    const o0 = document.createElement('option');
    o0.value = '';
    o0.textContent = placeholder;
    selectEl.appendChild(o0);

    rows.forEach(r => {
        const o = document.createElement('option');
        o.value = r.id;
        o.textContent = r.name;
        if (selectedValue && selectedValue === r.id) {
            o.selected = true;
        }
        selectEl.appendChild(o);
    });
    
    selectEl.disabled = false;
}

function disableSelect(selectEl, placeholder) {
    selectEl.disabled = true;
    selectEl.innerHTML = `<option value="">${placeholder}</option>`;
}

// DOM elements
const districtSel = document.getElementById('districtSel');
const blockSel = document.getElementById('blockSel');
const gpSel = document.getElementById('gpSel');

// Load blocks when district changes
districtSel.addEventListener('change', async function() {
    const did = this.value;
    
    // Disable downstream selects
    disableSelect(blockSel, '-- Select Block --');
    disableSelect(gpSel, '-- Select GP --');
    
    if (!did) {
        // Redirect to clear selection (or just update URL)
        const url = new URL(window.location.href);
        url.searchParams.delete('district_id');
        url.searchParams.delete('block_id');
        window.location.href = url.toString();
        return;
    }
    
    // Update URL without reload
    const url = new URL(window.location.href);
    url.searchParams.set('district_id', did);
    url.searchParams.delete('block_id');
    window.location.href = url.toString(); // Reload to get blocks from server
});

// Load GPs when block changes
blockSel.addEventListener('change', function() {
    const bid = this.value;
    
    disableSelect(gpSel, '-- Select GP --');
    
    if (!bid) {
        const url = new URL(window.location.href);
        url.searchParams.delete('block_id');
        window.location.href = url.toString();
        return;
    }
    
    const url = new URL(window.location.href);
    url.searchParams.set('block_id', bid);
    window.location.href = url.toString(); // Reload to get GPs from server
});

// Form validation
document.getElementById('addSchoolForm').addEventListener('submit', function(e) {
    const gp = document.querySelector('[name="gp_id"]').value;
    const schoolId = document.querySelector('[name="school_id"]').value;
    const name = document.querySelector('[name="name"]').value;
    
    if (!gp) {
        e.preventDefault();
        alert('Please select a Gram Panchayat');
        return;
    }
    
    if (!schoolId.trim()) {
        e.preventDefault();
        alert('Please enter a School ID');
        return;
    }
    
    if (!name.trim()) {
        e.preventDefault();
        alert('Please enter a School Name');
        return;
    }
});

// Pre-select GP if coming from URL (optional)
<?php if (isset($_GET['gp_id']) && !empty($_GET['gp_id'])): ?>
window.addEventListener('load', function() {
    const gpSelect = document.getElementById('gpSel');
    for (let i = 0; i < gpSelect.options.length; i++) {
        if (gpSelect.options[i].value === '<?= htmlspecialchars($_GET['gp_id']) ?>') {
            gpSelect.selectedIndex = i;
            break;
        }
    }
});
<?php endif; ?>
</script>

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