<?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 = 'Create Invoice';

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

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

$error = '';
$success = '';
$invoice_id = null;

// ======================================================
// 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';

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

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

$schoolStmt->execute();

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

// ======================================================
// 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();

                // ==========================================
                // GENERATE INVOICE NUMBER
                // ==========================================

                $invoice_no = 'INV-' . strtoupper(substr(md5(time()), 0, 8));

                // ==========================================
                // INSERT INVOICE
                // ==========================================

                $stmt = $pdo->prepare("
                    INSERT INTO invoices
                    (
                        school_id,
                        invoice_no,
                        plan_name,
                        amount,
                        billing_cycle,
                        start_date,
                        end_date,
                        payment_status,
                        payment_method,
                        remarks
                    )
                    VALUES
                    (
                        ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
                    )
                ");

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

                $invoice_id = $pdo->lastInsertId();

                // ==========================================
                // 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'             => 'CREATE',

                        'record_id'          => $invoice_id,

                        'message'            => "Invoice created: {$invoice_no}",

                        'old_data'           => null,

                        'new_data'           => [

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

                } catch (Exception $log_error) {

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

                $success = 'Invoice created successfully!';

                $_POST = [];

            }

            catch (Exception $e) {

                $pdo->rollBack();

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

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

// ======================================================
// GENERATE 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>

                    Create Invoice

                </h1>

            </div>

        </div>

    </div>

</section>

<!-- Main Content -->

<section class="content">

    <div class="container-fluid">

        <div class="card card-primary">

            <div class="card-header">

                <h3 class="card-title">

                    Invoice Management

                </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>

                                    Select School

                                </label>

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

                                    <option value="">

                                        Select School

                                    </option>

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

                                        <option
                                            value="<?= $school['id']; ?>"
                                        >

                                            <?= 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($_POST['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($_POST['amount'] ?? ''); ?>"
                                >

                            </div>

                        </div>

                        <!-- BILLING CYCLE -->

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

                            <div class="form-group">

                                <label>

                                    Billing Cycle

                                </label>

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

                                    <option value="Yearly">

                                        Yearly

                                    </option>

                                    <option value="Monthly">

                                        Monthly

                                    </option>

                                    <option value="Quarterly">

                                        Quarterly

                                    </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">

                                        Paid

                                    </option>

                                    <option value="Pending">

                                        Pending

                                    </option>

                                    <option value="Cancelled">

                                        Cancelled

                                    </option>

                                </select>

                            </div>

                        </div>

                        <!-- START DATE -->

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

                            <div class="form-group">

                                <label>

                                    Start Date

                                </label>

                                <input
                                    type="date"
                                    name="start_date"
                                    class="form-control"
                                    required
                                >

                            </div>

                        </div>

                        <!-- END DATE -->

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

                            <div class="form-group">

                                <label>

                                    End Date

                                </label>

                                <input
                                    type="date"
                                    name="end_date"
                                    class="form-control"
                                    required
                                >

                            </div>

                        </div>

                        <!-- PAYMENT 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($_POST['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($_POST['remarks'] ?? ''); ?>"
                                >

                            </div>

                        </div>

                    </div>

                </div>

                <div class="card-footer">

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

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

                        Create Invoice

                    </button>

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

                        Back

                    </a>

                </div>

            </form>

        </div>

    </div>

</section>

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