<?php ob_start(); session_start();

// request_outpass.php
require_once 'db.php';
require_once 'otp_sms_helper.php';

if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: admin_login.php'); exit;
}

$pageTitle = "Outpass - ";
require_once 'config.php';
include_once '_header.php';
include_once '_sidebar.php';

if (!isset($_GET['reg']) || $_GET['reg'] === '') {
    die('Invalid request');
}
$reg = $_GET['reg'];

// Fetch student
$st = $conn->prepare("SELECT unique_reg_number, full_name, class_grade, section, admission_number,
                             father_guardian_mobile, mother_mobile, school
                      FROM students WHERE unique_reg_number = ?");
$st->bind_param("s", $reg);
$st->execute();
$student = $st->get_result()->fetch_assoc();
$st->close();
if (!$student) { die('Student not found'); }

// Handle POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $reason = trim($_POST['reason'] ?? '');
    if ($reason === '') {
        $error = "Please enter a reason.";
    }

    $returndate = trim($_POST['returndate'] ?? '');
    if ($returndate === '') {
        $error = "Please enter a Return Date.";
    }

    // Handle upload
    $photoPath = null;
    if (!isset($error) && isset($_FILES['currentPhoto']) && $_FILES['currentPhoto']['error'] !== UPLOAD_ERR_NO_FILE) {
        $file = $_FILES['currentPhoto'];
        if ($file['error'] === UPLOAD_ERR_OK) {
            $allowed = ['image/jpeg','image/jpg','image/png'];
            // Use getimagesize() as fallback
            $imgInfo = @getimagesize($file['tmp_name']);
            $mime    = $imgInfo['mime'] ?? '';
            if (!in_array($mime, $allowed, true)) {
                $error = "Only JPG/PNG images are allowed.";
            } elseif ($file['size'] > 2 * 1024 * 1024) {
                $error = "Photo must be less than 2MB.";
            } else {
                $dir = __DIR__ . '/uploads/outpass';
                if (!is_dir($dir)) {
                    @mkdir($dir, 0777, true);
                }
                $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
                $fname = 'outpass_' . $student['unique_reg_number'] . '_' . time() . '.' . strtolower($ext);
                $dest = $dir . '/' . $fname;
                if (!move_uploaded_file($file['tmp_name'], $dest)) {
                    $error = "Failed to upload photo.";
                } else {
                    $photoPath = 'uploads/outpass/' . $fname; // relative path for web
                }
            }
        } else {
            $error = "Upload error (code: {$file['error']}).";
        }
    }
    if (!isset($error)) {
        // Insert outpass
        $otp = generate_otp();
        $ins = $conn->prepare("INSERT INTO student_outpass
                               (unique_reg_number, reason, photo_path, otp_code, otp_verified,returndate)
                               VALUES (?,?,?,?,0,?)");
        $ins->bind_param("sssss", $student['unique_reg_number'], $reason, $photoPath, $otp, $returndate);
        if ($ins->execute()) {
            $outpassId = $ins->insert_id;
            $ins->close();
            // Send OTP to father & mother (same OTP)
            //$msg = "OTP for ".$student['full_name']." outpass: $otp";
            if (!empty($student['father_guardian_mobile'])) {
                sendOtp($student['father_guardian_mobile'],$student['full_name'], $otp);
            }
            if (!empty($student['mother_mobile'])) {
                sendOtp($student['mother_mobile'],$student['full_name'], $otp);
            }
            // Keep for debug shown on verify page (do not remove in dev)
            $_SESSION['__last_outpass_otp'] = $otp;

            header('Location: verify_outpass.php?id='.$outpassId);
            exit;
        } else {
            $error = "Failed to create outpass. Please try again.";
        }
    }
}
?>
<main class="container-fluid">
    <h5 class="mb-4">Request Outpass</h5>
    <?php if (!empty($error)): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>
    <div class="card mb-3">
        <div class="card-header">Student</div>
        <div class="card-body row">
            <div class="col-md-6 mb-2"><strong>Name:</strong> <?= htmlspecialchars($student['full_name']) ?></div>
            <div class="col-md-3 mb-2"><strong>Class:</strong> <?= htmlspecialchars($student['class_grade']) ?></div>
            <div class="col-md-3 mb-2"><strong>Section:</strong> <?= htmlspecialchars($student['section']) ?></div>
            <div class="col-md-4 mb-2"><strong>Admission No:</strong> <?= htmlspecialchars($student['admission_number']) ?></div>
            <div class="col-md-4 mb-2"><strong>Father Mobile:</strong> <?= mask_middle4(htmlspecialchars($student['father_guardian_mobile'])) ?></div>
            <div class="col-md-4 mb-2"><strong>Mother Mobile:</strong> <?= mask_middle4(htmlspecialchars($student['mother_mobile'])) ?></div>
            <div class="col-md-4 mb-2"><strong>School:</strong> <?= htmlspecialchars($student['school']) ?></div>
        </div>
    </div>
    <form method="POST" enctype="multipart/form-data" class="card">
        <div class="card-header">Outpass Details</div>
        <div class="card-body row g-3">
            <div class="col-md-12">
                <label class="form-label">Reason for Outpass <span class="text-danger">*</span></label>
                <textarea name="reason" class="form-control" rows="3" required><?= htmlspecialchars($_POST['reason'] ?? '') ?></textarea>
            </div>
             <div class="col-md-6">
                <label class="form-label">Return Date</label>
                <input type="date" name="returndate"  class="form-control" required>
            </div>
            <div class="col-md-6">
                <label class="form-label">Upload Current Photo (JPG/PNG, &lt; 2MB)</label>
                <input type="file" name="currentPhoto" accept="image/jpeg,image/png" class="form-control">
            </div>
        </div>
        <div class="card-footer text-end">
            <a class="btn btn-secondary" href="student_outpass.php">Back</a>
            <button class="btn btn-primary" type="submit">Send OTP & Continue</button>
        </div>
    </form>
</main>
<?php include_once 'footer.php'; ?>
