<?php
// ============================================================================
// school_step9_save.php
// ============================================================================

// Start session
require_once 'session_config_school.php';

// Validate school session
if (!validateSchoolSession()) {
    header("Location: login.php");
    exit;
}

// Database connection
require_once 'connect.php';

// Debug - log what's being received (remove in production)
error_log("School Step9 POST data received: " . print_r($_POST, true));

// Check if this is a POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $_SESSION['error_message'] = "Invalid request method. Please use the form to submit data.";
    header("Location: school_step9.php");
    exit();
}

// Check if we have any POST data
if (empty($_POST)) {
    $_SESSION['error_message'] = "No form data received. Please try again.";
    header("Location: school_step9.php");
    exit();
}

// Check for required fields
if (!isset($_POST['emis_code']) || empty($_POST['emis_code'])) {
    $_SESSION['error_message'] = "School EMIS code is missing.";
    header("Location: school_step9.php");
    exit();
}

// Check if SMC selection is present
if (!isset($_POST['smc_select']) || empty($_POST['smc_select'])) {
    $_SESSION['error_message'] = "Please select whether the school has an SMC.";
    header("Location: school_step9.php");
    exit();
}

try {
    // Begin transaction
    $conn->begin_transaction();

    // Get form data
    $emis_code = $_POST['emis_code'];
    $smc_select = $_POST['smc_select'] ?? '';
    
    // Initialize variables with defaults
    $smc_active = null;
    $smc_training = null;
    $smc_president_name = null;
    $smc_president_contact = null;
    $smc_bank_account = null;
    $smc_bank_name = null;
    $smc_bank_account_number = null;
    $smc_amount_received = 0.00;
    $no_smc_reason = null;

    // Validate SMC selection
    if (!in_array($smc_select, ['yes', 'no'])) {
        throw new Exception("Invalid SMC selection.");
    }

    // Process based on SMC selection
    if ($smc_select === 'yes') {
        // SMC exists - validate required fields
        $smc_active = $_POST['smcactive'] ?? '';
        $smc_training = $_POST['smctraining'] ?? '';
        $smc_bank_account = $_POST['smcbankaccount'] ?? '';

        if (empty($smc_active) || !in_array($smc_active, ['Yes', 'No'])) {
            throw new Exception("Please select whether SMC is active.");
        }
        if (empty($smc_training) || !in_array($smc_training, ['Yes', 'No'])) {
            throw new Exception("Please select whether SMC has received training.");
        }
        if (empty($smc_bank_account) || !in_array($smc_bank_account, ['Yes', 'No'])) {
            throw new Exception("Please select whether SMC has a bank account.");
        }

        // Optional fields
        $smc_president_name = !empty($_POST['smcp']) ? trim($_POST['smcp']) : null;
        $smc_president_contact = !empty($_POST['smcpc']) ? trim($_POST['smcpc']) : null;

        // Validate and format phone number if provided
        if ($smc_president_contact) {
            // Remove any non-digit characters
            $clean_phone = preg_replace('/\D/', '', $smc_president_contact);
            
            // Check if it's exactly 10 digits and doesn't start with zero
            if (!preg_match('/^[1-9]\d{9}$/', $clean_phone)) {
                throw new Exception("Please enter a valid 10-digit Pakistan phone number (no leading zero).");
            }
            
            // Add +92 prefix for database storage
            $smc_president_contact = '+92' . $clean_phone;
        }

        // Bank details if Yes
        if ($smc_bank_account === 'Yes') {
            $smc_bank_name = !empty($_POST['smcbankname']) ? trim($_POST['smcbankname']) : null;
            $smc_bank_account_number = !empty($_POST['smcbac']) ? trim($_POST['smcbac']) : null;

            if (empty($smc_bank_name)) {
                throw new Exception("Please enter bank name.");
            }
            if (empty($smc_bank_account_number)) {
                throw new Exception("Please enter account number.");
            }

            $smc_amount_received = !empty($_POST['smcamount']) ? floatval($_POST['smcamount']) : 0.00;
        }

    } else {
        // No SMC - validate reason with minimum 50 characters
        $no_smc_reason = !empty($_POST['nosmc']) ? trim($_POST['nosmc']) : null;
        
        if (empty($no_smc_reason)) {
            throw new Exception("Please provide a reason for not having an SMC.");
        }
        
        if (strlen($no_smc_reason) < 50) {
            throw new Exception("The reason for not having an SMC must be at least 50 characters long. Current length: " . strlen($no_smc_reason) . " characters.");
        }
    }

    // Check if record already exists for this EMIS code
    $check_query = "SELECT id FROM school_smc WHERE emis_code = ?";
    $check_stmt = $conn->prepare($check_query);
    $check_stmt->bind_param("s", $emis_code);
    $check_stmt->execute();
    $result = $check_stmt->get_result();
    $existing_record = $result->fetch_assoc();

    if ($existing_record) {
        // UPDATE existing record
        $update_query = "UPDATE school_smc SET 
            smc_select = ?,
            smc_active = ?,
            smc_training = ?,
            smc_president_name = ?,
            smc_president_contact = ?,
            smc_bank_account = ?,
            smc_bank_name = ?,
            smc_bank_account_number = ?,
            smc_amount_received = ?,
            no_smc_reason = ?,
            updated_at = CURRENT_TIMESTAMP
            WHERE emis_code = ?";

        $update_stmt = $conn->prepare($update_query);
        $update_stmt->bind_param(
            "ssssssssdss",
            $smc_select,
            $smc_active,
            $smc_training,
            $smc_president_name,
            $smc_president_contact,
            $smc_bank_account,
            $smc_bank_name,
            $smc_bank_account_number,
            $smc_amount_received,
            $no_smc_reason,
            $emis_code
        );

        if (!$update_stmt->execute()) {
            throw new Exception("Failed to update SMC record: " . $update_stmt->error);
        }

        $action = "updated";
        error_log("Updated SMC record for EMIS: $emis_code");

    } else {
        // INSERT new record
        $insert_query = "INSERT INTO school_smc (
            emis_code,
            smc_select,
            smc_active,
            smc_training,
            smc_president_name,
            smc_president_contact,
            smc_bank_account,
            smc_bank_name,
            smc_bank_account_number,
            smc_amount_received,
            no_smc_reason,
            created_at,
            updated_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)";

        $insert_stmt = $conn->prepare($insert_query);
        $insert_stmt->bind_param(
            "sssssssssds",
            $emis_code,
            $smc_select,
            $smc_active,
            $smc_training,
            $smc_president_name,
            $smc_president_contact,
            $smc_bank_account,
            $smc_bank_name,
            $smc_bank_account_number,
            $smc_amount_received,
            $no_smc_reason
        );

        if (!$insert_stmt->execute()) {
            // Check for duplicate key error
            if ($conn->errno == 1062) {
                throw new Exception("An SMC record for this school already exists.");
            } else {
                throw new Exception("Failed to insert SMC record: " . $insert_stmt->error);
            }
        }

        $action = "saved";
        error_log("Inserted new SMC record for EMIS: $emis_code");
    }

    // Commit transaction
    $conn->commit();

    // Set success message
    $_SESSION['success_message'] = "SMC information $action successfully.";

    // Clear any stored form data
    if (isset($_SESSION['form_data'])) {
        unset($_SESSION['form_data']);
    }

    // Redirect to next step (Step 10)
    header("Location: school_step10.php");
    exit();

} catch (Exception $e) {
    // Rollback on error
    $conn->rollback();
    error_log("School Step9 Save Error: " . $e->getMessage());

    // Store form data and error for repopulation
    $_SESSION['form_data'] = $_POST;
    $_SESSION['error_message'] = "Error saving SMC data: " . $e->getMessage();

    // Redirect back to step 9
    header("Location: school_step9.php");
    exit();
}
?>