<?php

session_start();

require_once __DIR__ . '/../../library/config.php';
require_once __DIR__ . '/../../library/super_admin_auth.php';
require_once __DIR__ . '/../../library/super_admin_audit_log.php';

$page_title = 'Edit Invoice';

require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/sidebar.php';

// ======================================================
// DEFAULT VARIABLES
// ======================================================

$error = '';
$success = '';

// ======================================================
// VALIDATE ID
// ======================================================

$invoice_id = (int) ($_GET['id'] ?? 0);

if ($invoice_id <= 0) {

    header('Location: view_invoices.php');
    exit;
}

// ======================================================
// FETCH INVOICE
// ======================================================

$stmt = $pdo->prepare("
    SELECT *
    FROM invoices
    WHERE id = ?
    LIMIT 1
");

$stmt->execute([$invoice_id]);

$invoice = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$invoice) {

    header('Location: view_invoices.php');
    exit;
}

// ======================================================
// FETCH SCHOOLS
// ======================================================

$schoolStmt = $pdo->prepare("
    SELECT
        id,
        name
    FROM schools
    WHERE status = 'active'
    ORDER BY name ASC
");

$schoolStmt->execute();

$schools = $schoolStmt->fetchAll(PDO::FETCH_ASSOC);

// ======================================================
// SUPER ADMIN DATA
// ======================================================

$super_admin_id = $_SESSION['super_admin_id'] ?? null;
$super_admin_name = $_SESSION['super_admin_name'] ?? 'Unknown';
$super_admin_email = $_SESSION['super_admin_email'] ?? 'Unknown';

// ======================================================
// FORM SUBMIT
// ======================================================

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // ==================================================
    // CSRF VALIDATION
    // ==================================================

    if (
        !isset($_POST['csrf_token']) ||
        !hash_equals($_SESSION['csrf_token'] ?? '', $_POST['csrf_token'])
    ) {
        $error = 'Invalid request.';
    }

    else {

        // ==============================================
        // GET FORM DATA
        // ==============================================

        $school_id = (int) ($_POST['school_id'] ?? 0);

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

        $amount = (float) ($_POST['amount'] ?? 0);

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

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

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

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

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

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

        // ==============================================
        // VALIDATION
        // ==============================================

        if (
            $school_id <= 0 ||
            empty($plan_name) ||
            $amount <= 0 ||
            empty($billing_cycle) ||
            empty($start_date) ||
            empty($end_date) ||
            empty($payment_status)
        ) {
            $error = 'All required fields are mandatory.';
        }

        else {

            try {

                // ==========================================
                // START TRANSACTION
                // ==========================================

                $pdo->beginTransaction();

                // ==========================================
                // UPDATE INVOICE
                // ==========================================

                $updateStmt = $pdo->prepare("
                    UPDATE invoices
                    SET
                        school_id = ?,
                        plan_name = ?,
                        amount = ?,
                        billing_cycle = ?,
                        start_date = ?,
                        end_date = ?,
                        payment_status = ?,
                        payment_method = ?,
                        remarks = ?
                    WHERE id = ?
                ");

                $updateStmt->execute([
                    $school_id,
                    $plan_name,
                    $amount,
                    $billing_cycle,
                    $start_date,
                    $end_date,
                    $payment_status,
                    $payment_method,
                    $remarks,
                    $invoice_id
                ]);

                // ==========================================
                // UPDATE SUBSCRIPTION
                // ==========================================

                if ($payment_status === 'Paid') {

                    $subscriptionStmt = $pdo->prepare("
                        UPDATE schools
                        SET
                            subscription_status = 'Active',
                            subscription_start = ?,
                            subscription_end = ?
                        WHERE id = ?
                    ");

                    $subscriptionStmt->execute([
                        $start_date,
                        $end_date,
                        $school_id
                    ]);
                }

                // ==========================================
                // COMMIT
                // ==========================================

                $pdo->commit();

                // ==========================================
                // AUDIT LOG
                // ==========================================

                try {

                    logSuperAdminActivity($pdo, [

                        'super_admin_id'     => $super_admin_id,
                        'super_admin_email'  => $super_admin_email,
                        'super_admin_name'   => $super_admin_name,

                        'module'             => 'Invoice Management',

                        'action'             => 'UPDATE',

                        'record_id'          => $invoice_id,

                        'message'            => "Invoice updated: {$invoice['invoice_no']}",

                        'old_data'           => $invoice,

                        'new_data'           => [

                            'school_id'       => $school_id,
                            'plan_name'       => $plan_name,
                            'amount'          => $amount,
                            'billing_cycle'   => $billing_cycle,
                            'payment_status'  => $payment_status
                        ]
                    ]);

                } catch (Exception $log_error) {

                    error_log(
                        'EDIT INVOICE AUDIT ERROR: ' .
                        $log_error->getMessage()
                    );
                }

                $success = 'Invoice updated successfully!';

                // ==========================================
                // REFRESH DATA
                // ==========================================

                $stmt->execute([$invoice_id]);

                $invoice = $stmt->fetch(PDO::FETCH_ASSOC);

            }

            catch (Exception $e) {

                $pdo->rollBack();

                error_log(
                    'EDIT INVOICE ERROR: ' .
                    $e->getMessage()
                );

                $error = 'Something went wrong. Please try again.';
            }
        }
    }
}

// ======================================================
// CSRF TOKEN
// ======================================================

if (empty($_SESSION['csrf_token'])) {

    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

?>

<!-- Content Header -->

<section class="content-header">

    <div class="container-fluid">

        <div class="row mb-2">

            <div class="col-sm-6">

                <h1>

                    Edit Invoice

                </h1>

            </div>

        </div>

    </div>

</section>

<!-- Main Content -->

<section class="content">

    <div class="container-fluid">

        <div class="card card-warning">

            <div class="card-header">

                <h3 class="card-title">

                    Update Invoice

                </h3>

            </div>

            <form method="POST">

                <input
                    type="hidden"
                    name="csrf_token"
                    value="<?= htmlspecialchars($_SESSION['csrf_token']); ?>"
                >

                <div class="card-body">

                    <?php if ($error): ?>

                        <div class="alert alert-danger">

                            <?= htmlspecialchars($error); ?>

                        </div>

                    <?php endif; ?>

                    <?php if ($success): ?>

                        <div class="alert alert-success">

                            <?= htmlspecialchars($success); ?>

                        </div>

                    <?php endif; ?>

                    <div class="row">

                        <!-- SCHOOL -->

                        <div class="col-md-6">

                            <div class="form-group">

                                <label>

                                    School

                                </label>

                                <select
                                    name="school_id"
                                    class="form-control"
                                    required
                                >

                                    <?php foreach ($schools as $school): ?>

                                        <option
                                            value="<?= $school['id']; ?>"
                                            <?= ($invoice['school_id'] == $school['id']) ? 'selected' : ''; ?>
                                        >

                                            <?= htmlspecialchars($school['name']); ?>

                                        </option>

                                    <?php endforeach; ?>

                                </select>

                            </div>

                        </div>

                        <!-- PLAN -->

                        <div class="col-md-6">

                            <div class="form-group">

                                <label>

                                    Plan Name

                                </label>

                                <input
                                    type="text"
                                    name="plan_name"
                                    class="form-control"
                                    required
                                    value="<?= htmlspecialchars($invoice['plan_name']); ?>"
                                >

                            </div>

                        </div>

                        <!-- AMOUNT -->

                        <div class="col-md-4">

                            <div class="form-group">

                                <label>

                                    Amount

                                </label>

                                <input
                                    type="number"
                                    name="amount"
                                    class="form-control"
                                    required
                                    min="0"
                                    step="0.01"
                                    value="<?= htmlspecialchars($invoice['amount']); ?>"
                                >

                            </div>

                        </div>

                        <!-- BILLING -->

                        <div class="col-md-4">

                            <div class="form-group">

                                <label>

                                    Billing Cycle

                                </label>

                                <select
                                    name="billing_cycle"
                                    class="form-control"
                                    required
                                >

                                    <option
                                        value="Monthly"
                                        <?= ($invoice['billing_cycle'] === 'Monthly') ? 'selected' : ''; ?>
                                    >
                                        Monthly
                                    </option>

                                    <option
                                        value="Quarterly"
                                        <?= ($invoice['billing_cycle'] === 'Quarterly') ? 'selected' : ''; ?>
                                    >
                                        Quarterly
                                    </option>

                                    <option
                                        value="Yearly"
                                        <?= ($invoice['billing_cycle'] === 'Yearly') ? 'selected' : ''; ?>
                                    >
                                        Yearly
                                    </option>

                                </select>

                            </div>

                        </div>

                        <!-- STATUS -->

                        <div class="col-md-4">

                            <div class="form-group">

                                <label>

                                    Payment Status

                                </label>

                                <select
                                    name="payment_status"
                                    class="form-control"
                                    required
                                >

                                    <option
                                        value="Paid"
                                        <?= ($invoice['payment_status'] === 'Paid') ? 'selected' : ''; ?>
                                    >
                                        Paid
                                    </option>

                                    <option
                                        value="Pending"
                                        <?= ($invoice['payment_status'] === 'Pending') ? 'selected' : ''; ?>
                                    >
                                        Pending
                                    </option>

                                    <option
                                        value="Cancelled"
                                        <?= ($invoice['payment_status'] === 'Cancelled') ? 'selected' : ''; ?>
                                    >
                                        Cancelled
                                    </option>

                                </select>

                            </div>

                        </div>

                        <!-- START -->

                        <div class="col-md-6">

                            <div class="form-group">

                                <label>

                                    Start Date

                                </label>

                                <input
                                    type="date"
                                    name="start_date"
                                    class="form-control"
                                    required
                                    value="<?= htmlspecialchars($invoice['start_date']); ?>"
                                >

                            </div>

                        </div>

                        <!-- END -->

                        <div class="col-md-6">

                            <div class="form-group">

                                <label>

                                    End Date

                                </label>

                                <input
                                    type="date"
                                    name="end_date"
                                    class="form-control"
                                    required
                                    value="<?= htmlspecialchars($invoice['end_date']); ?>"
                                >

                            </div>

                        </div>

                        <!-- METHOD -->

                        <div class="col-md-6">

                            <div class="form-group">

                                <label>

                                    Payment Method

                                </label>

                                <input
                                    type="text"
                                    name="payment_method"
                                    class="form-control"
                                    value="<?= htmlspecialchars($invoice['payment_method']); ?>"
                                >

                            </div>

                        </div>

                        <!-- REMARKS -->

                        <div class="col-md-6">

                            <div class="form-group">

                                <label>

                                    Remarks

                                </label>

                                <input
                                    type="text"
                                    name="remarks"
                                    class="form-control"
                                    value="<?= htmlspecialchars($invoice['remarks']); ?>"
                                >

                            </div>

                        </div>

                    </div>

                </div>

                <div class="card-footer">

                    <button
                        type="submit"
                        class="btn btn-warning"
                    >

                        <i class="fas fa-save"></i>

                        Update Invoice

                    </button>

                    <a
                        href="view_invoices.php"
                        class="btn btn-secondary"
                    >

                        Back

                    </a>

                </div>

            </form>

        </div>

    </div>

</section>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>