<!-- 
  **File Structure:**
  - school_step1.php (School Profile)
  - school_step2.php (School Land)
  - school_step3.php (School Building)
  - school_step4.php (School Facilities)
  - school_step5.php (School Posts)
  - school_step6.php (School Students)
  - school_step7.php (School Board Results)
  - school_step8.php (School Budget)
  - school_step9.php (School SMC)
  - school_step10.php (School Location and View)
  
  Here's the tenth file (school_step10.php):
    -->
	
	<?php
/**
* School Step 10: Photo Upload and Collage Generation
* Final step of school profile registration - DISPLAY ONLY
*/
require_once 'session_config_school.php';
if (!validateSchoolSession()) {
    header("Location: login.php");
    exit;
}
require_once 'school_profile_completion_check.php';
include_once 'connect.php';
require_once 'photo_config.php';

error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/logs/school_step10_errors.log');

function get_session_value($key, $default = '') {
    return isset($_SESSION[$key]) ? $_SESSION[$key] : $default;
}

function getExistingPhotos($conn, $emis_code) {
    $photos = [];
    $stmt = $conn->prepare("SELECT id, photo_type, file_path, description, uploaded_at FROM school_photos WHERE emis_code = ? ORDER BY uploaded_at DESC");
    if ($stmt) {
        $stmt->bind_param("s", $emis_code);
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) $photos[] = $row;
        $stmt->close();
    }
    return $photos;
}

function getLatestCollage($conn, $emis_code) {
    $stmt = $conn->prepare("SELECT collage_filename, generated_at FROM school_collages WHERE emis_code = ? ORDER BY generated_at DESC LIMIT 1");
    if ($stmt) {
        $stmt->bind_param("s", $emis_code);
        $stmt->execute();
        $result = $stmt->get_result();
        $collage = $result->fetch_assoc();
        $stmt->close();
        return $collage;
    }
    return null;
}

// ============================================================================
// MAIN EXECUTION
// ============================================================================
$success_message = '';
$error_message = '';

if (!isset($_SESSION['school_name']) || !isset($_SESSION['emis_code'])) {
    header("Location: login.php");
    exit();
}

$school_name = get_session_value('school_name', '');
$emis_code = get_session_value('emis_code', '');

if (isset($_SESSION['success_message'])) {
    $success_message = $_SESSION['success_message'];
    unset($_SESSION['success_message']);
}

if (isset($_SESSION['error_message'])) {
    $error_message = $_SESSION['error_message'];
    unset($_SESSION['error_message']);
}

$upload_dir = UPLOAD_BASE_PATH . "{$emis_code}/";
if (!file_exists($upload_dir)) mkdir($upload_dir, 0755, true);

if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(openssl_random_pseudo_bytes(32));
}

// Get existing photos (for display only - NOT for counting)
$existing_photos = getExistingPhotos($conn, $emis_code);
$existing_photo_types = [];
if (!empty($existing_photos)) {
    foreach ($existing_photos as $photo) {
        $existing_photo_types[] = $photo['photo_type'];
    }
}
$existing_photo_types_json = json_encode($existing_photo_types);

$latest_collage = getLatestCollage($conn, $emis_code);

// ✅ Check if profile has photos (to show "Mark Complete" button)
$has_photos = !empty($existing_photos) || ($latest_collage && file_exists($upload_dir . $latest_collage['collage_filename']));
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>School Location and Photos Registration - Step 10 of 10</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<style>
*{margin:0;padding:0;box-sizing:border-box}body{font-family:'Segoe UI',Tahoma,Geneva,Verdana,sans-serif;background:#f5f7fa;color:#333;line-height:1.6}.container{max-width:1200px;margin:0 auto;padding:20px}.header{text-align:center;margin-bottom:30px;padding:25px;background:linear-gradient(135deg,#2c3e50,#4a6491);color:#fff;border-radius:10px;box-shadow:0 4px 15px rgba(0,0,0,.1)}.header h1{font-size:28px;margin-bottom:10px}.header p{opacity:.9;font-size:16px}.progress-container{display:flex;justify-content:space-between;align-items:center;margin-bottom:30px;position:relative;max-width:100%}.progress-container::before{content:"";position:absolute;top:50%;left:0;right:0;height:4px;background:#e0e0e0;transform:translateY(-50%);z-index:1}.progress-bar{position:absolute;top:50%;left:0;height:4px;background:#3498db;transform:translateY(-50%);z-index:2;transition:width .3s ease;width:100%}.step{display:flex;flex-direction:column;align-items:center;position:relative;z-index:3;width:100px}.step span:first-child{width:40px;height:40px;border-radius:50%;background:#e0e0e0;color:#666;display:flex;align-items:center;justify-content:center;font-weight:700;margin-bottom:8px;border:3px solid #fff;transition:all .3s ease}.step.completed span:first-child{background:#2ecc71;color:#fff}.step.active span:first-child{background:#3498db;color:#fff;transform:scale(1.1)}.step-label{font-size:12px;text-align:center;color:#666;font-weight:500;max-width:100px;word-wrap:break-word}.step.completed .step-label{color:#2ecc71}.step.active .step-label{color:#3498db;font-weight:600}.form-container{background:#fff;border-radius:10px;border-left:4px solid #3498db;padding:30px;box-shadow:0 5px 20px rgba(0,0,0,.08);margin-bottom:30px}.school-info{background:#f8f9fa;padding:15px;border-radius:6px;margin-bottom:20px;border-left:4px solid #3498db}.school-info h3{color:#2c3e50;margin-bottom:10px;font-size:16px;display:flex;align-items:center;gap:10px}.school-info p{color:#666;font-size:14px}.info-box{background:#e8f6f3;border-left:4px solid #1abc9c;padding:20px;margin-bottom:25px;border-radius:8px}.info-box h4{color:#16a085;margin-bottom:10px;font-size:16px;display:flex;align-items:center;gap:8px}.info-box p{color:#555;font-size:14px;line-height:1.6}.requirements-box{background:linear-gradient(135deg,#fff3cd,#ffeaa7);border-left:4px solid #ffa502;padding:25px;margin-bottom:25px;border-radius:10px;box-shadow:0 2px 10px rgba(255,165,2,.1)}.requirements-box h3{color:#d35400;margin-bottom:15px;font-size:18px;display:flex;align-items:center;gap:10px}.requirements-list{display:grid;grid-template-columns:repeat(auto-fit,minmax(250px,1fr));gap:15px;margin-top:15px}.requirement-item{background:#fff;padding:15px;border-radius:6px;box-shadow:0 2px 5px rgba(0,0,0,.05);display:flex;align-items:center;gap:10px}.req-mandatory{border-left:4px solid #e74c3c}.req-optional{border-left:4px solid #f39c12}.req-icon{font-size:20px;width:30px;text-align:center}.req-mandatory .req-icon{color:#e74c3c}.req-optional .req-icon{color:#f39c12}.req-text h4{color:#2c3e50;font-size:14px;margin-bottom:5px}.req-text p{color:#7f8c8d;font-size:12px}.upload-section{background:#f8f9fa;padding:25px;border-radius:8px;margin-bottom:25px}.photo-row{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:20px;margin-bottom:25px}.photo-upload-box{background:#fff;padding:20px;border-radius:8px;box-shadow:0 3px 10px rgba(0,0,0,.08);text-align:center;border:2px dashed #ddd;transition:all .4s cubic-bezier(.4,0,.2,1);position:relative;overflow:hidden}.photo-upload-box::before{content:'';position:absolute;top:0;left:-100%;width:100%;height:100%;background:linear-gradient(90deg,transparent,rgba(255,255,255,.3),transparent);transition:left .5s}.photo-upload-box:hover::before{left:100%}.photo-upload-box:hover{border-color:#3498db;transform:translateY(-2px)}.photo-upload-box.mandatory{border-color:#e74c3c;background:#fff5f5}.photo-upload-box.optional{border-color:#f39c12;background:#fff9e6}.photo-icon{font-size:40px;color:#3498db;margin-bottom:15px}.photo-upload-box.mandatory .photo-icon{color:#e74c3c}.photo-upload-box.optional .photo-icon{color:#f39c12}.photo-title{font-weight:600;margin-bottom:10px;color:#2c3e50}.photo-subtitle{font-size:12px;color:#7f8c8d;margin-bottom:15px}.replace-warning{background:linear-gradient(135deg,#fff3cd,#ffeaa7);border-left:4px solid #ffa502;padding:20px;border-radius:10px;margin-bottom:25px;box-shadow:0 2px 10px rgba(255,165,2,.1);display:flex;align-items:center;gap:15px}.replace-warning i{font-size:28px;color:#d35400}.replace-warning p{margin:0;color:#856404;font-weight:500}.file-input-wrapper{position:relative;overflow:hidden;display:inline-block;margin-bottom:10px}.file-input-wrapper input[type=file]{position:absolute;left:0;top:0;opacity:0;width:100%;height:100%;cursor:pointer}.file-btn{display:inline-block;padding:10px 20px;background:#3498db;color:#fff;border-radius:4px;font-size:14px;font-weight:600;cursor:pointer;transition:all .3s ease}.file-btn:hover{background:#2980b9}.preview-container{margin-top:15px;min-height:100px}.photo-preview{max-width:100%;max-height:150px;border-radius:4px;box-shadow:0 2px 5px rgba(0,0,0,.1);display:none}.photo-status{font-size:12px;margin-top:5px;padding:5px;border-radius:3px}.status-success{background:#d4edda;color:#155724}.status-error{background:#f8d7da;color:#721c24}.existing-photos{background:#e8f6f3;padding:25px;border-radius:8px;margin-top:30px;border-left:4px solid #1abc9c}.existing-photos h3{color:#16a085;margin-bottom:20px;display:flex;align-items:center;gap:10px}.photos-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:15px}.photo-card{background:#fff;border-radius:6px;overflow:hidden;box-shadow:0 3px 10px rgba(0,0,0,.1)}.photo-card img{width:100%;height:120px;object-fit:cover}.photo-card .caption{padding:10px;font-size:12px;color:#2c3e50;text-align:center;background:#f8f9fa}.collage-section{background:linear-gradient(135deg,#fff5f5,#ffe6e6);padding:25px;border-radius:8px;margin-top:30px;border-left:4px solid #e74c3c}.collage-section h3{color:#c0392b;margin-bottom:20px;display:flex;align-items:center;gap:10px}.collage-container{text-align:center;margin:20px 0}.collage-image{max-width:100%;height:auto;border-radius:10px;box-shadow:0 8px 25px rgba(0,0,0,.15);border:8px solid #fff;transition:transform .3s ease}.collage-image:hover{transform:scale(1.02)}@keyframes successPulse{0%,100%{transform:scale(1);box-shadow:0 0 0 0 rgba(46,204,113,.4)}50%{transform:scale(1.02);box-shadow:0 0 0 10px rgba(46,204,113,0)}}.alert-success{animation:successPulse 1s ease}.collage-actions{margin-top:20px;display:flex;justify-content:center;gap:15px;flex-wrap:wrap}.collage-btn{padding:12px 25px;background:linear-gradient(135deg,#3498db,#2980b9);color:#fff;border:none;border-radius:6px;font-size:14px;font-weight:600;cursor:pointer;transition:all .3s ease;display:flex;align-items:center;gap:8px}.collage-btn:hover{transform:translateY(-2px);box-shadow:0 6px 15px rgba(52,152,219,.3)}.collage-btn.download{background:linear-gradient(135deg,#2ecc71,#27ae60)}.collage-btn.share{background:linear-gradient(135deg,#9b59b6,#8e44ad)}.collage-btn.print{background:linear-gradient(135deg,#e67e22,#d35400)}.collage-info{background:#fff;padding:15px;border-radius:6px;margin-top:20px;text-align:center;font-size:14px;color:#666;box-shadow:0 3px 10px rgba(0,0,0,.08)}.collage-timestamp{font-weight:700;color:#2c3e50}@keyframes fadeInCollage{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}.new-collage{animation:fadeInCollage .8s ease}.navigation-buttons{display:flex;justify-content:space-between;margin-top:40px;margin-bottom:0;padding-top:20px;border-top:1px solid #eee}.nav-btn{padding:12px 30px;background:linear-gradient(135deg,#3498db,#2980b9);color:#fff;border:none;border-radius:6px;font-size:16px;font-weight:600;cursor:pointer;transition:all .3s ease;display:flex;align-items:center;gap:10px}.nav-btn:hover{transform:translateY(-2px);box-shadow:0 6px 15px rgba(52,152,219,.3);background:linear-gradient(135deg,#2980b9,#1c5d87)}.nav-btn:active{transform:translateY(0)}.nav-btn:disabled{background:#95a5a6;cursor:not-allowed;transform:none;box-shadow:none}.nav-btn.back{background:linear-gradient(135deg,#7f8c8d,#95a5a6)}.nav-btn.back:hover{background:linear-gradient(135deg,#95a5a6,#7f8c8d);box-shadow:0 6px 15px rgba(127,140,141,.3)}.loading-spinner{display:inline-block;width:20px;height:20px;border:3px solid rgba(255,255,255,.3);border-radius:50%;border-top-color:#fff;animation:spin 1s ease-in-out infinite;margin-right:10px;vertical-align:middle}@keyframes spin{to{transform:rotate(360deg)}}@keyframes fadeIn{from{opacity:0}to{opacity:1}}.photo-preview-container{position:relative;display:inline-block;margin-top:10px}.photo-preview{max-width:100%;max-height:150px;border-radius:8px;box-shadow:0 4px 8px rgba(0,0,0,.1);transition:transform .3s ease}.photo-preview:hover{transform:scale(1.05)}.preview-overlay{position:absolute;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,.5);color:#fff;display:flex;align-items:center;justify-content:center;opacity:0;transition:opacity .3s ease;border-radius:8px}.photo-preview-container:hover .preview-overlay{opacity:1}.remove-photo{position:absolute;top:5px;right:5px;background:#e74c3c;color:#fff;border:none;border-radius:50%;width:25px;height:25px;cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:16px;transition:all .3s ease;z-index:10}.remove-photo:hover{background:#c0392b;transform:scale(1.1)}.photo-upload-box.has-preview{border-style:solid;border-width:3px}.photo-upload-box.has-preview.mandatory{border-color:#2ecc71}.photo-upload-box.has-preview.optional{border-color:#f39c12}.file-info{font-size:11px;color:#7f8c8d;margin-top:5px;text-align:left}.alert{padding:15px;border-radius:6px;margin-bottom:20px;text-align:center;font-weight:500}.alert-success{background:#d4edda;color:#155724;border:1px solid #c3e6cb}.alert-error{background:#f8d7da;color:#721c24;border:1px solid #f5c6cb}.counter{text-align:center;margin:20px 0;font-size:16px;color:#2c3e50}.counter span{font-weight:700;color:#3498db}@media(max-width:768px){.container{padding:10px}.form-container{padding:20px}.header{padding:20px 15px}.header h1{font-size:24px}.photo-row{grid-template-columns:1fr}.photos-grid{grid-template-columns:repeat(auto-fill,minmax(150px,1fr))}.collage-actions{flex-direction:column;align-items:center}.collage-btn{width:100%;max-width:300px;justify-content:center}.progress-container{overflow-x:auto;padding-bottom:20px}.navigation-buttons{flex-direction:column;gap:15px}.nav-btn{width:100%;justify-content:center}}

/* ✅ NEW: Complete Profile Button Styles */
.complete-section {
    margin-top: 30px;
    padding: 25px;
    background: linear-gradient(135deg, #27ae60, #2ecc71);
    border-radius: 10px;
    text-align: center;
    box-shadow: 0 4px 15px rgba(46, 204, 113, 0.3);
}
.complete-section h3 {
    color: white;
    margin-bottom: 15px;
    font-size: 20px;
}
.complete-section p {
    color: rgba(255,255,255,0.9);
    margin-bottom: 20px;
    font-size: 14px;
}
.complete-btn {
    padding: 15px 40px;
    background: white;
    color: #27ae60;
    border: none;
    border-radius: 8px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    display: inline-flex;
    align-items: center;
    gap: 10px;
    box-shadow: 0 4px 10px rgba(0,0,0,0.1);
}
.complete-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(0,0,0,0.15);
}
.complete-btn:disabled {
    opacity: 0.6;
    cursor: not-allowed;
    transform: none;
}
</style>
</head>
<body>
<?php include 'floating_logout_school.php'; ?>
<div class="container">
    <div class="header">
        <h1><i class="fas fa-camera"></i> School Location and Photos Registration - Step 10 of 10</h1>
        <p>Complete all 10 steps to register a new school in Districts Schools Management System</p>
    </div>
    <div class="progress-container">
        <div class="progress-bar" id="progressBar"></div>
        <div class="step completed" id="step1"><span>1</span><span class="step-label">School Profile</span></div>
        <div class="step completed" id="step2"><span>2</span><span class="step-label">School Land</span></div>
        <div class="step completed" id="step3"><span>3</span><span class="step-label">School Building</span></div>
        <div class="step completed" id="step4"><span>4</span><span class="step-label">School Facilities</span></div>
        <div class="step completed" id="step5"><span>5</span><span class="step-label">School Posts</span></div>
        <div class="step completed" id="step6"><span>6</span><span class="step-label">Students</span></div>
        <div class="step completed" id="step7"><span>7</span><span class="step-label">Board Results</span></div>
        <div class="step completed" id="step8"><span>8</span><span class="step-label">Budget</span></div>
        <div class="step completed" id="step9"><span>9</span><span class="step-label">SMC</span></div>
        <div class="step active" id="step10"><span>10</span><span class="step-label">Location & Photos</span></div>
    </div>
    <?php if(!empty($success_message)): ?>
    <div class="alert alert-success"><i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($success_message); ?></div>
    <?php endif; ?>
    <?php if(!empty($error_message)): ?>
    <div class="alert alert-error"><i class="fas fa-exclamation-circle"></i> <?php echo htmlspecialchars($error_message); ?></div>
    <?php endif; ?>
    <div class="form-container">
        <div class="school-info">
            <h3><i class="fas fa-info-circle"></i> School Location and Photos</h3>
            <p>Upload photos of your school facilities for <strong><?php echo htmlspecialchars($school_name); ?></strong> (EMIS: <strong><?php echo htmlspecialchars($emis_code); ?></strong>). All mandatory photos must be uploaded.</p>
        </div>
        <div class="info-box">
            <h4><i class="fas fa-info-circle"></i> About School Photos</h4>
            <p>Upload clear, high-quality photos of your school facilities. These photos help in documentation, verification, and showcasing your school's infrastructure. All mandatory photos must be uploaded. A professional collage will be automatically generated.</p>
        </div>
        <div class="requirements-box">
            <h3><i class="fas fa-clipboard-check"></i> Photo Requirements</h3>
            <p>Please upload clear, high-quality photos of your school facilities. All mandatory photos must be uploaded.</p>
            <div class="requirements-list">
                <div class="requirement-item req-mandatory"><div class="req-icon"><i class="fas fa-door-open"></i></div><div class="req-text"><h4>School Entrance (Mandatory)</h4><p>Clear photo of main school entrance/gate showing school name</p></div></div>
                <div class="requirement-item req-mandatory"><div class="req-icon"><i class="fas fa-school"></i></div><div class="req-text"><h4>School Building (Mandatory)</h4><p>Full view of main school building from front</p></div></div>
                <div class="requirement-item req-mandatory"><div class="req-icon"><i class="fas fa-running"></i></div><div class="req-text"><h4>Playground (Mandatory)</h4><p>Photo of school playground or sports facilities</p></div></div>
                <div class="requirement-item req-optional"><div class="req-icon"><i class="fas fa-users"></i></div><div class="req-text"><h4>Assembly Area (Optional)</h4><p>Assembly hall or morning assembly area</p></div></div>
                <div class="requirement-item req-optional"><div class="req-icon"><i class="fas fa-flask"></i></div><div class="req-text"><h4>Science Labs (Optional)</h4><p>Science laboratory or computer lab</p></div></div>
            </div>
        </div>
        <form method="POST" action="school_step10_save.php" enctype="multipart/form-data" id="photoForm">
            <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
            <div class="upload-section">
                <h3 style="margin-bottom:20px;color:#2c3e50"><i class="fas fa-upload"></i> Upload New Photos</h3>
                <div class="replace-warning"><i class="fas fa-exclamation-triangle"></i><p><strong>Important:</strong> Uploading new photos will REPLACE all existing photos. You must select at least <?php echo MIN_PHOTOS; ?> new photos to proceed.</p></div>
                <div class="counter">New Photos Selected: <span id="selectedCount">0</span> / Required: <?php echo MIN_PHOTOS; ?> / Max Total: <?php echo MAX_PHOTOS; ?></div>
                <div class="photo-row">
                    <div class="photo-upload-box mandatory" id="entranceBox"><div class="photo-icon"><i class="fas fa-door-open"></i></div><div class="photo-title">School Entrance</div><div class="photo-subtitle">Main entrance/gate (Mandatory)</div><div class="file-input-wrapper"><button type="button" class="file-btn"><i class="fas fa-camera"></i> Choose Photo</button><input type="file" name="school_photos[]" accept="image/*" data-type="entrance" onchange="previewPhoto(this,'entrance')"></div><input type="hidden" name="photo_types[]" value="entrance"><div class="preview-container" id="entrancePreview"><img src="" class="photo-preview" id="entranceImg"><div class="photo-status" id="entranceStatus"></div></div></div>
                    <div class="photo-upload-box mandatory" id="buildingBox"><div class="photo-icon"><i class="fas fa-school"></i></div><div class="photo-title">School Building</div><div class="photo-subtitle">Main building front view (Mandatory)</div><div class="file-input-wrapper"><button type="button" class="file-btn"><i class="fas fa-camera"></i> Choose Photo</button><input type="file" name="school_photos[]" accept="image/*" data-type="building" onchange="previewPhoto(this,'building')"></div><input type="hidden" name="photo_types[]" value="building"><div class="preview-container" id="buildingPreview"><img src="" class="photo-preview" id="buildingImg"><div class="photo-status" id="buildingStatus"></div></div></div>
                    <div class="photo-upload-box mandatory" id="playgroundBox"><div class="photo-icon"><i class="fas fa-running"></i></div><div class="photo-title">Playground</div><div class="photo-subtitle">Sports/play area (Mandatory)</div><div class="file-input-wrapper"><button type="button" class="file-btn"><i class="fas fa-camera"></i> Choose Photo</button><input type="file" name="school_photos[]" accept="image/*" data-type="playground" onchange="previewPhoto(this,'playground')"></div><input type="hidden" name="photo_types[]" value="playground"><div class="preview-container" id="playgroundPreview"><img src="" class="photo-preview" id="playgroundImg"><div class="photo-status" id="playgroundStatus"></div></div></div>
                </div>
                <div class="photo-row">
                    <div class="photo-upload-box optional" id="assemblyBox"><div class="photo-icon"><i class="fas fa-users"></i></div><div class="photo-title">Assembly Area</div><div class="photo-subtitle">Assembly hall (Optional)</div><div class="file-input-wrapper"><button type="button" class="file-btn"><i class="fas fa-camera"></i> Choose Photo</button><input type="file" name="school_photos[]" accept="image/*" data-type="assembly" onchange="previewPhoto(this,'assembly')"></div><input type="hidden" name="photo_types[]" value="assembly"><div class="preview-container" id="assemblyPreview"><img src="" class="photo-preview" id="assemblyImg"><div class="photo-status" id="assemblyStatus"></div></div></div>
                    <div class="photo-upload-box optional" id="labsBox"><div class="photo-icon"><i class="fas fa-flask"></i></div><div class="photo-title">Science Labs</div><div class="photo-subtitle">Laboratory (Optional)</div><div class="file-input-wrapper"><button type="button" class="file-btn"><i class="fas fa-camera"></i> Choose Photo</button><input type="file" name="school_photos[]" accept="image/*" data-type="labs" onchange="previewPhoto(this,'labs')"></div><input type="hidden" name="photo_types[]" value="labs"><div class="preview-container" id="labsPreview"><img src="" class="photo-preview" id="labsImg"><div class="photo-status" id="labsStatus"></div></div></div>
                </div>
            </div>
            
            <?php if($latest_collage && file_exists($upload_dir . $latest_collage['collage_filename'])): ?>
            <div class="collage-section">
                <h3><i class="fas fa-images"></i> Current Photo Collage</h3>
                <p>This collage will be replaced when you upload new photos.</p>
                <div class="collage-container">
                    <img src="<?php echo htmlspecialchars($upload_dir . $latest_collage['collage_filename']); ?>?t=<?php echo time(); ?>" alt="School Photo Collage" class="collage-image" onerror="this.style.display='none';document.getElementById('collageError').style.display='block'">
                    <div id="collageError" style="display:none;color:#e74c3c;padding:20px"><i class="fas fa-exclamation-triangle"></i> Collage preview not available.</div>
                </div>
                
                <!-- ✅ FIX: Collage buttons moved inside the collage section -->
                <div class="collage-actions">
                    <button type="button" class="collage-btn download" onclick="downloadCollage('<?php echo $latest_collage['collage_filename']; ?>')">
                        <i class="fas fa-download"></i> Download Collage
                    </button>
                    <button type="button" class="collage-btn share" onclick="shareCollage('<?php echo $latest_collage['collage_filename']; ?>')">
                        <i class="fas fa-share-alt"></i> Share
                    </button>
                    <button type="button" class="collage-btn print" onclick="printCollage('<?php echo $latest_collage['collage_filename']; ?>')">
                        <i class="fas fa-print"></i> Print
                    </button>
                </div>
                
                <div class="collage-info">
                    <i class="fas fa-info-circle"></i> Generated on: <span class="collage-timestamp"><?php echo date('F j, Y g:i A', strtotime($latest_collage['generated_at'])); ?></span>
                </div>
            </div>
            <?php endif; ?>
            
            <?php if(!empty($existing_photos)): ?>
            <div class="existing-photos">
                <h3><i class="fas fa-history"></i> Existing Photos (Will be replaced)</h3>
                <div class="photos-grid">
                    <?php foreach($existing_photos as $photo): ?>
                    <div class="photo-card">
                        <img src="<?php echo htmlspecialchars($upload_dir . $photo['file_path']); ?>?t=<?php echo time(); ?>" alt="<?php echo htmlspecialchars($photo['description']); ?>" onerror="this.src='data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjAwIiBoZWlnaHQ9IjEyMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMjAwIiBoZWlnaHQ9IjEyMCIgZmlsbD0iI2UwZTBlMCIvPjx0ZXh0IHg9IjEwMCIgeT0iNjAiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIxMiIgZmlsbD0iIzY2NiIgdGV4dC1hbmNob3I9Im1pZGRsZSI+U2Nob29sIFBob3RvPC90ZXh0Pjwvc3ZnPg=='">
                        <div class="caption"><i class="fas fa-<?php switch($photo['photo_type']){case'entrance':echo'door-open';break;case'building':echo'school';break;case'playground':echo'running';break;case'assembly':echo'users';break;case'labs':echo'flask';break;default:echo'camera';} ?>"></i> <?php echo htmlspecialchars($photo['description']); ?></div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>
            
            <div class="navigation-buttons">
                <button type="button" class="nav-btn back" onclick="window.location.href='school_step9.php'"><i class="fas fa-arrow-left"></i> Back</button>
                <button type="submit" class="nav-btn" id="submitBtn" disabled>
                    <i class="fas fa-exclamation-triangle"></i> Select <?php echo MIN_PHOTOS; ?> new photos to upload
                </button>
            </div>
        </form>
        
        <!-- ✅ NEW: Mark School Profile Completed Section -->
        <?php if($has_photos): ?>
        <div class="complete-section">
            <h3><i class="fas fa-check-circle"></i> All Steps Completed!</h3>
            <p>Your school profile is ready. Click below to mark it as complete and go to your dashboard.</p>
            <button type="button" class="complete-btn" id="markCompleteBtn" onclick="markProfileComplete()">
                <i class="fas fa-flag-checkered"></i> Mark School Profile Completed
            </button>
        </div>
        <?php endif; ?>
        
    </div>
</div>
<script>
// selectedPhotos tracks ONLY new photos being selected
let selectedPhotos = {
    entrance: false,
    building: false,
    playground: false,
    assembly: false,
    labs: false
};

// We track existing photos but they DON'T count toward the minimum
const existingPhotoTypes = <?php echo $existing_photo_types_json; ?>;
console.log('Existing photos (for reference only):', existingPhotoTypes);

// This counts ONLY newly selected photos
let newPhotoCount = 0;

function previewPhoto(input, type) {
    const preview = document.getElementById(type + 'Img');
    const status = document.getElementById(type + 'Status');
    const box = document.getElementById(type + 'Box');
    const previewContainer = document.getElementById(type + 'Preview');
    
    // Remove existing remove button if any
    $(box).find('.remove-photo').remove();

    if (input.files && input.files[0]) {
        const file = input.files[0];
        const reader = new FileReader();

        // Validate file size
        if (file.size > <?php echo MAX_FILE_SIZE; ?>) {
            status.textContent = 'File too large (max 5MB)';
            status.className = 'photo-status status-error';
            input.value = '';
            
            // Only decrement if this photo was previously selected as NEW
            if (selectedPhotos[type] === true) {
                newPhotoCount--;
            }
            selectedPhotos[type] = false;
            updateCounter();
            return;
        }

        // Validate file type
        const validTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
        if (!validTypes.includes(file.type)) {
            status.textContent = 'Invalid file type';
            status.className = 'photo-status status-error';
            input.value = '';
            
            // Only decrement if this photo was previously selected as NEW
            if (selectedPhotos[type] === true) {
                newPhotoCount--;
            }
            selectedPhotos[type] = false;
            updateCounter();
            return;
        }

        reader.onload = function(e) {
            preview.src = e.target.result;
            preview.style.display = 'block';
            status.textContent = 'Ready to upload - ' + (file.size / 1024).toFixed(1) + ' KB';
            status.className = 'photo-status status-success';
            box.style.borderColor = '#2ecc71';
            box.style.backgroundColor = '#f0f9f0';
            box.classList.add('has-preview');

            // Add remove button
            const removeBtn = document.createElement('button');
            removeBtn.type = 'button';
            removeBtn.className = 'remove-photo';
            removeBtn.innerHTML = '<i class="fas fa-times"></i>';
            removeBtn.onclick = function() { removePhoto(this, type); };
            box.appendChild(removeBtn);

            // Add file info
            const fileInfo = document.createElement('div');
            fileInfo.className = 'file-info';
            fileInfo.innerHTML = '<i class="fas fa-info-circle"></i> ' + file.name + ' (' + (file.size / 1024).toFixed(1) + ' KB)';
            previewContainer.appendChild(fileInfo);

            // Only increment if this is a NEW selection (not previously selected)
            if (selectedPhotos[type] === false) {
                newPhotoCount++;
            }
            selectedPhotos[type] = true;
            updateCounter();
        };

        reader.readAsDataURL(file);
    } else {
        // If no file selected, remove from selectedPhotos
        preview.style.display = 'none';
        status.textContent = '';
        box.classList.remove('has-preview');
        box.style.borderColor = (type === 'entrance' || type === 'building' || type === 'playground') ? '#e74c3c' : '#f39c12';
        box.style.backgroundColor = (type === 'entrance' || type === 'building' || type === 'playground') ? '#fff5f5' : '#fff9e6';
        
        // Only decrement if this was previously selected as NEW
        if (selectedPhotos[type] === true) {
            newPhotoCount--;
        }
        selectedPhotos[type] = false;
        updateCounter();
    }
}

function removePhoto(btn, type) {
    const box = document.getElementById(type + 'Box');
    const fileInput = box.querySelector('input[type="file"]');
    const preview = document.getElementById(type + 'Img');
    const status = document.getElementById(type + 'Status');
    const previewContainer = document.getElementById(type + 'Preview');

    // Clear file input
    fileInput.value = '';

    // Hide preview
    preview.style.display = 'none';

    // Clear status
    status.textContent = '';
    status.className = 'photo-status';

    // Remove file info and button
    $(previewContainer).find('.file-info').remove();
    $(btn).remove();

    // Reset box style
    box.classList.remove('has-preview');
    box.style.borderColor = (type === 'entrance' || type === 'building' || type === 'playground') ? '#e74c3c' : '#f39c12';
    box.style.backgroundColor = (type === 'entrance' || type === 'building' || type === 'playground') ? '#fff5f5' : '#fff9e6';

    // Only decrement if this was selected as NEW
    if (selectedPhotos[type] === true) {
        newPhotoCount--;
    }
    selectedPhotos[type] = false;
    updateCounter();
}

function updateCounter() {
    // Count only NEW photos (existing photos are ignored)
    document.getElementById('selectedCount').textContent = newPhotoCount;
    
    const submitBtn = document.getElementById('submitBtn');
    const minPhotos = <?php echo MIN_PHOTOS; ?>;
    
    console.log('New photos selected:', newPhotoCount);

    // Enable button ONLY when at least MIN_PHOTOS NEW photos are selected
    if (newPhotoCount >= minPhotos) {
        submitBtn.disabled = false;
        submitBtn.innerHTML = '<i class="fas fa-save"></i> Upload ' + newPhotoCount + ' New Photos & Replace Existing';
        submitBtn.style.opacity = '1';
        submitBtn.style.cursor = 'pointer';
    } else {
        submitBtn.disabled = true;
        const needed = minPhotos - newPhotoCount;
        submitBtn.innerHTML = '<i class="fas fa-exclamation-triangle"></i> Select ' + needed + ' more new photo' + (needed > 1 ? 's' : '');
        submitBtn.style.opacity = '0.6';
        submitBtn.style.cursor = 'not-allowed';
    }
}

function downloadCollage(filename) {
    const link = document.createElement('a');
    link.href = 'download_collage.php?file=' + encodeURIComponent(filename) + '&emis=<?php echo $emis_code; ?>&t=' + Date.now();
    link.download = 'School_Collage_' + new Date().toISOString().split('T')[0] + '.jpg';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

function shareCollage(filename) {
    const shareUrl = window.location.origin + '/<?php echo $upload_dir; ?>' + filename;
    const shareText = 'Check out our school photo collage from <?php echo $school_name; ?>!';
    
    if (navigator.share) {
        navigator.share({
            title: 'School Photo Collage',
            text: shareText,
            url: shareUrl
        }).catch(console.error);
    } else {
        const tempInput = document.createElement('input');
        tempInput.value = shareText + ' ' + shareUrl;
        document.body.appendChild(tempInput);
        tempInput.select();
        document.execCommand('copy');
        document.body.removeChild(tempInput);
        alert('Link copied to clipboard!\n' + shareText + '\n' + shareUrl);
    }
}

function printCollage(filename) {
    const printWindow = window.open('<?php echo $upload_dir; ?>' + filename + '?t=' + Date.now(), '_blank');
    printWindow.onload = function() {
        setTimeout(function() {
            printWindow.print();
        }, 500);
    };
}

// ✅ NEW: Mark Profile Complete Function
function markProfileComplete() {
    const btn = document.getElementById('markCompleteBtn');
    
    // Show loading state
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Completing...';
    btn.disabled = true;
    
    // Redirect to school dashboard
    // Update this path to match your actual dashboard location
    window.location.href = 'school_dashboard.php';
}

$(document).ready(function() {
    // Call updateCounter on page load - button starts disabled
    updateCounter();

    $('#photoForm').on('submit', function(e) {
        // Check for mandatory photos in the NEW selection
        // Since we're replacing everything, all mandatory photos must be in the new selection
        const missingMandatory = [];
        
        if (!selectedPhotos.entrance) missingMandatory.push('School Entrance');
        if (!selectedPhotos.building) missingMandatory.push('School Building');
        if (!selectedPhotos.playground) missingMandatory.push('Playground');

        if (missingMandatory.length > 0) {
            e.preventDefault();
            alert('Missing mandatory photos in your selection:\n' + missingMandatory.join('\n') + '\n\nAll mandatory photos must be included in your new upload.');
            return false;
        }

        // Check for minimum NEW photos
        if (newPhotoCount < <?php echo MIN_PHOTOS; ?>) {
            e.preventDefault();
            alert('You must select at least <?php echo MIN_PHOTOS; ?> NEW photos to upload. You have selected ' + newPhotoCount + ' new photos.');
            return false;
        }

        // Check maximum total photos
        const totalSelected = Object.values(selectedPhotos).filter(Boolean).length;
        if (totalSelected > <?php echo MAX_PHOTOS; ?>) {
            e.preventDefault();
            alert('Maximum <?php echo MAX_PHOTOS; ?> photos allowed. You have selected ' + totalSelected + ' photos.');
            return false;
        }

        // Show loading state
        $('#submitBtn').html('<span class="loading-spinner"></span> Uploading and Generating Collage...');
        $('#submitBtn').prop('disabled', true);
        return true;
    });

    // Drag and drop functionality
    const boxes = document.querySelectorAll('.photo-upload-box');
    boxes.forEach(box => {
        box.addEventListener('dragover', function(e) {
            e.preventDefault();
            this.style.borderColor = '#3498db';
            this.style.backgroundColor = '#e8f4fc';
            this.style.transform = 'scale(1.02)';
        });

        box.addEventListener('dragleave', function(e) {
            e.preventDefault();
            const type = this.id.replace('Box', '');
            this.style.borderColor = (type === 'entrance' || type === 'building' || type === 'playground') ? '#e74c3c' : '#f39c12';
            this.style.backgroundColor = (type === 'entrance' || type === 'building' || type === 'playground') ? '#fff5f5' : '#fff9e6';
            this.style.transform = 'scale(1)';
        });

        box.addEventListener('drop', function(e) {
            e.preventDefault();
            const type = this.id.replace('Box', '');
            const fileInput = this.querySelector('input[type="file"]');

            if (e.dataTransfer.files.length) {
                fileInput.files = e.dataTransfer.files;
                $(fileInput).trigger('change');
                previewPhoto(fileInput, type);
            }

            this.style.borderColor = (type === 'entrance' || type === 'building' || type === 'playground') ? '#e74c3c' : '#f39c12';
            this.style.backgroundColor = (type === 'entrance' || type === 'building' || type === 'playground') ? '#fff5f5' : '#fff9e6';
            this.style.transform = 'scale(1)';
        });
    });

    <?php if(!empty($success_message)): ?>
    setTimeout(() => {
        window.scrollTo({ top: 0, behavior: 'smooth' });
    }, 100);
    <?php endif; ?>
});
</script>
</body>
</html>