<?php
require_once('db.php');

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method.']);
    exit();
}

$type = trim($_POST['type'] ?? '');

if ($type === 'leave') {
    $student_name = trim($_POST['student_name'] ?? '');
    $father_name = trim($_POST['father_name'] ?? '');
    $school_name = trim($_POST['school_name'] ?? 'B.S. Public School');
    $class_name = trim($_POST['class_name'] ?? '');
    $section = trim($_POST['section'] ?? '');
    $roll_no = trim($_POST['roll_no'] ?? '');
    $from_date = trim($_POST['from_date'] ?? '');
    $to_date = trim($_POST['to_date'] ?? '');
    $reason_type = trim($_POST['reason_type'] ?? '');
    $reason_details = trim($_POST['reason_details'] ?? '');
    $parent_mobile = trim($_POST['parent_mobile'] ?? '');

    if (empty($student_name) || empty($father_name) || empty($class_name) || empty($from_date) || empty($to_date) || empty($reason_type) || empty($parent_mobile)) {
        echo json_encode(['status' => 'error', 'message' => 'Kripya sabhi zaroori fields (Student Name, Father Name, Class, Dates, Reason, Mobile) bharein.']);
        exit();
    }

    // Calculate days
    $d1 = new DateTime($from_date);
    $d2 = new DateTime($to_date);
    $diff = $d1->diff($d2);
    $total_days = ($diff->invert == 0) ? ($diff->days + 1) : 1;
    if ($diff->invert == 1) {
        $to_date = $from_date;
        $total_days = 1;
    }

    $app_no = 'BSPS-LV-' . date('ymd') . '-' . rand(100, 999);

    if ($db_connected) {
        $stmt = $conn->prepare("INSERT INTO leave_applications (app_no, school_name, student_name, father_name, class_name, section, roll_no, from_date, to_date, total_days, reason_type, reason_details, parent_mobile, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'Pending')");
        $stmt->bind_param("sssssssssisss", $app_no, $school_name, $student_name, $father_name, $class_name, $section, $roll_no, $from_date, $to_date, $total_days, $reason_type, $reason_details, $parent_mobile);
        $stmt->execute();
    }

    $whatsapp_msg = "🏫 *BSPS & AHIS - STUDENT LEAVE APPLICATION*\n"
                  . "━━━━━━━━━━━━━━━━━━━━\n"
                  . "🆔 *Application No:* {$app_no}\n"
                  . "👤 *Student Name:* {$student_name}\n"
                  . "👨‍👦 *Father's Name:* {$father_name}\n"
                  . "🏫 *School/Branch:* {$school_name}\n"
                  . "📚 *Class & Section:* {$class_name} " . ($section ? "({$section})" : "") . "\n"
                  . "📅 *Leave Duration:* " . date('d M Y', strtotime($from_date)) . " to " . date('d M Y', strtotime($to_date)) . " ({$total_days} Day/s)\n"
                  . "📝 *Reason for Leave:* {$reason_type}\n"
                  . ($reason_details ? "💬 *Details:* {$reason_details}\n" : "")
                  . "📞 *Parent Mobile:* {$parent_mobile}\n"
                  . "━━━━━━━━━━━━━━━━━━━━\n"
                  . "✅ *Status:* Submitted to School Admin Box";

    echo json_encode([
        'status' => 'success',
        'app_no' => $app_no,
        'student_name' => $student_name,
        'message' => 'Chutti ki application safaltapoorvak submit ho gayi hai aur Admin Portal me bhej di gayi hai.',
        'whatsapp_msg' => $whatsapp_msg
    ]);
    exit();
}

if ($type === 'tc') {
    $student_name = trim($_POST['student_name'] ?? '');
    $father_name = trim($_POST['father_name'] ?? '');
    $school_name = trim($_POST['school_name'] ?? 'B.S. Public School');
    $class_name = trim($_POST['class_name'] ?? '');
    $scholar_no = trim($_POST['scholar_no'] ?? '');
    $reason_for_leaving = trim($_POST['reason_for_leaving'] ?? '');
    $parent_mobile = trim($_POST['parent_mobile'] ?? '');

    if (empty($student_name) || empty($father_name) || empty($class_name) || empty($reason_for_leaving) || empty($parent_mobile)) {
        echo json_encode(['status' => 'error', 'message' => 'Kripya sabhi zaroori details (Student Name, Father Name, Class, Reason, Mobile) bharein.']);
        exit();
    }

    $app_no = 'BSPS-TC-' . date('ymd') . '-' . rand(100, 999);

    if ($db_connected) {
        $stmt = $conn->prepare("INSERT INTO tc_applications (app_no, school_name, student_name, father_name, class_name, scholar_no, reason_for_leaving, parent_mobile, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'Under Process')");
        $stmt->bind_param("ssssssss", $app_no, $school_name, $student_name, $father_name, $class_name, $scholar_no, $reason_for_leaving, $parent_mobile);
        $stmt->execute();
    }

    $whatsapp_msg = "🏫 *BSPS & AHIS - TC APPLICATION REQUEST*\n"
                  . "━━━━━━━━━━━━━━━━━━━━\n"
                  . "🆔 *Application No:* {$app_no}\n"
                  . "👤 *Student Name:* {$student_name}\n"
                  . "👨‍👦 *Father's Name:* {$father_name}\n"
                  . "🏫 *School/Branch:* {$school_name}\n"
                  . "📚 *Class Last Studied:* {$class_name}\n"
                  . ($scholar_no ? "📋 *Scholar/Admn No:* {$scholar_no}\n" : "")
                  . "📝 *Reason for TC:* {$reason_for_leaving}\n"
                  . "📞 *Parent Mobile:* {$parent_mobile}\n"
                  . "━━━━━━━━━━━━━━━━━━━━\n"
                  . "✅ *Status:* Under Process at Admin Office";

    echo json_encode([
        'status' => 'success',
        'app_no' => $app_no,
        'student_name' => $student_name,
        'message' => 'Transfer Certificate (TC) application safaltapoorvak submit ho chuki hai.',
        'whatsapp_msg' => $whatsapp_msg
    ]);
    exit();
}

if ($type === 'admission') {
    $student_name = trim($_POST['student_name'] ?? '');
    $parent_name = trim($_POST['parent_name'] ?? '');
    $grade = trim($_POST['grade'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $address = trim($_POST['address'] ?? '');

    if (empty($student_name) || empty($parent_name) || empty($grade) || empty($phone)) {
        echo json_encode(['status' => 'error', 'message' => 'Please fill in all required admission fields.']);
        exit();
    }

    if ($db_connected) {
        $stmt = $conn->prepare("INSERT INTO admission_enquiries (student_name, parent_name, grade, phone, email, address, status) VALUES (?, ?, ?, ?, ?, ?, 'New')");
        $stmt->bind_param("ssssss", $student_name, $parent_name, $grade, $phone, $email, $address);
        $stmt->execute();
    }

    echo json_encode([
        'status' => 'success',
        'message' => 'Admission registration successfully submitted! Our counseling team will contact you soon.'
    ]);
    exit();
}

echo json_encode(['status' => 'error', 'message' => 'Invalid action type.']);
