<?php

ob_start();

require_once __DIR__ . '/../library/auth.php';

$school_id = $_SESSION['school_id'];

allow_roles(['admin', 'accountant']);

// ======================================================
// FETCH SCHOOL DETAILS
// ======================================================

$stmt = $pdo->prepare("
    SELECT
        id,
        name
    FROM schools
    WHERE id = ?
    LIMIT 1
");

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

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

if (!$school) {

    die('School not found.');
}

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

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

    $prefix       = trim($_POST['prefix'] ?? 'REC');

    $next_number  = (int)($_POST['next_number'] ?? 1);

    $padding      = (int)($_POST['padding'] ?? 6);

    $default_mode = trim($_POST['default_mode'] ?? 'Cash');

    // ==================================================
    // CHECK EXISTING SETTINGS
    // ==================================================

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

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

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

    // ==================================================
    // UPDATE SETTINGS
    // ==================================================

    if ($exists) {

        $stmt = $pdo->prepare("
            UPDATE receipt_settings

            SET

                prefix = ?,
                next_number = ?,
                padding = ?,
                default_mode = ?

            WHERE school_id = ?
        ");

        $stmt->execute([

            $prefix,

            $next_number,

            $padding,

            $default_mode,

            $school_id

        ]);

    }

    // ==================================================
    // INSERT SETTINGS
    // ==================================================

    else {

        $stmt = $pdo->prepare("
            INSERT INTO receipt_settings
            (
                school_id,
                school_name,
                prefix,
                next_number,
                padding,
                default_mode
            )

            VALUES
            (
                ?, ?, ?, ?, ?, ?
            )
        ");

        $stmt->execute([

            $school_id,

            $school['name'],

            $prefix,

            $next_number,

            $padding,

            $default_mode

        ]);
    }

    header(
        "Location: fees_settings.php?msg=Settings saved successfully"
    );

    exit;
}

// ======================================================
// FETCH SETTINGS
// ======================================================

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

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

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

// ======================================================
// RECEIPT PREVIEW
// ======================================================

$preview = '';

if ($settings) {

    $preview =
        $settings['prefix']
        . '-'
        . str_pad(
            $settings['next_number'],
            $settings['padding'],
            '0',
            STR_PAD_LEFT
        );
}

// ======================================================
// PAGE SETTINGS
// ======================================================

$page_title = 'Fees Settings';

require_once __DIR__ . '/../include/header.php';

require_once __DIR__ . '/../include/sidebar.php';

?>

<div class="content-wrapper">

    <section class="content-header">

        <div class="container-fluid">

            <div class="row mb-2">

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

                    <h1>Fees & Receipt Settings</h1>

                </div>

            </div>

        </div>

    </section>

    <section class="content">

        <div class="container-fluid">

            <?php if (isset($_GET['msg'])) : ?>

                <div class="alert alert-success">

                    <i class="icon fas fa-check"></i>

                    <?= htmlspecialchars($_GET['msg']) ?>

                </div>

            <?php endif; ?>

            <!-- ========================================= -->
            <!-- SETTINGS FORM -->
            <!-- ========================================= -->

            <div class="card card-outline card-primary">

                <div class="card-header">

                    <h3 class="card-title">

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

                        Configuration

                    </h3>

                </div>

                <form method="post">

                    <div class="card-body">

                        <div class="row">

                            <!-- SCHOOL NAME -->

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

                                <label>School Name</label>

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

                            </div>

                            <!-- RECEIPT PREFIX -->

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

                                <label>Receipt Prefix</label>

                                <input
                                    type="text"
                                    name="prefix"
                                    class="form-control"
                                    value="<?= htmlspecialchars($settings['prefix'] ?? 'REC') ?>"
                                    required
                                >

                            </div>

                            <!-- NEXT NUMBER -->

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

                                <label>Next Number</label>

                                <input
                                    type="number"
                                    name="next_number"
                                    class="form-control"
                                    value="<?= $settings['next_number'] ?? 1 ?>"
                                    required
                                >

                            </div>

                            <!-- ZERO PADDING -->

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

                                <label>Zero Padding</label>

                                <select
                                    name="padding"
                                    class="form-control"
                                >

                                    <?php

                                    foreach ([3,4,5,6,7,8] as $p) {

                                        $selected =
                                            (($settings['padding'] ?? 6) == $p)
                                            ? 'selected'
                                            : '';

                                        echo "
                                            <option value='{$p}' {$selected}>
                                                {$p} Digits
                                            </option>
                                        ";
                                    }

                                    ?>

                                </select>

                            </div>

                            <!-- DEFAULT MODE -->

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

                                <label>Default Payment Mode</label>

                                <select
                                    name="default_mode"
                                    class="form-control"
                                >

                                    <?php

                                    foreach (
                                        ['Cash', 'UPI', 'Card', 'Cheque']
                                        as $mode
                                    ) {

                                        $selected =
                                            (($settings['default_mode'] ?? 'Cash') == $mode)
                                            ? 'selected'
                                            : '';

                                        echo "
                                            <option value='{$mode}' {$selected}>
                                                {$mode}
                                            </option>
                                        ";
                                    }

                                    ?>

                                </select>

                            </div>

                        </div>

                    </div>

                    <div class="card-footer text-right">

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

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

                            Save Settings

                        </button>

                    </div>

                </form>

            </div>

            <!-- ========================================= -->
            <!-- PREVIEW -->
            <!-- ========================================= -->

            <?php if ($settings) : ?>

                <div class="card card-outline card-success">

                    <div class="card-header">

                        <h3 class="card-title">

                            Current Preview:

                            <span class="badge badge-success">

                                <?= htmlspecialchars($preview) ?>

                            </span>

                        </h3>

                    </div>

                    <div class="card-body p-0">

                        <table class="table table-striped">

                            <tbody>

                                <tr>

                                    <th>School Name</th>

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

                                </tr>

                                <tr>

                                    <th>Receipt Format</th>

                                    <td>

                                        <?= htmlspecialchars($settings['prefix']) ?>

                                        -

                                        (
                                        <?= str_repeat('0', $settings['padding'] - 1) . '1' ?>
                                        )

                                    </td>

                                </tr>

                                <tr>

                                    <th>Default Mode</th>

                                    <td>

                                        <span class="badge badge-info">

                                            <?= htmlspecialchars($settings['default_mode']) ?>

                                        </span>

                                    </td>

                                </tr>

                            </tbody>

                        </table>

                    </div>

                </div>

            <?php endif; ?>

        </div>

    </section>

</div>

<?php

ob_end_flush();

require_once __DIR__ . '/../include/footer.php';

?>