<?php
ob_start();
session_start();
require_once '../config/database.php';       // $pdo (Seven Credit DB)
require_once '../config/modules.php';         // company_enabled_modules(), module_on()
require_once '../config/module_access.php';   // mod_can_view(), mod_can_edit()

if (!isset($_SESSION['user_id']) || empty($_SESSION['company_id'])) {
    header('Location: ../auth/login.php'); exit;
}
$companyId   = (int)$_SESSION['company_id'];
$userId      = (int)$_SESSION['user_id'];
$role        = $_SESSION['role'] ?? '';
$companyName = $_SESSION['company_name'] ?? 'Company';

$enabled = company_enabled_modules($pdo, $companyId);
if (!module_on($enabled, 'jobs')) {
    http_response_code(403);
    exit('Job Management is not enabled for your company.');
}
if (!mod_can_admin($pdo, $companyId, $userId, $role, 'jobs')) {
    http_response_code(403);
    exit('You need Manage (admin) access for Job Management.');
}
if (!function_exists('esc')) {
    function esc($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
}

/*
|--------------------------------------------------------------------------
| Ensure sp_payment_types exists (auto-create if missing)
|--------------------------------------------------------------------------
*/
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS sp_payment_types (
        id INT AUTO_INCREMENT PRIMARY KEY, company_id INT NOT NULL,
        code VARCHAR(50) DEFAULT NULL, label VARCHAR(255) DEFAULT NULL, fee DECIMAL(15,2) NOT NULL DEFAULT 0,
        is_manual_fee TINYINT(1) NOT NULL DEFAULT 0, status VARCHAR(20) DEFAULT 'active', sort_order INT DEFAULT 0,
        INDEX(company_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
} catch (Throwable $e) {
    // ignore; errors surface on query below
}

$message = '';
$error   = '';

function makeCode($text)
{
    $text = strtolower(trim((string)$text));
    $text = preg_replace('/[^a-z0-9]+/', '_', $text);
    $text = trim($text, '_');
    return $text !== '' ? $text : 'payment_type';
}

/*
|--------------------------------------------------------------------------
| Add Payment Type (scoped by company_id)
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_payment_type'])) {
    $label         = trim($_POST['label'] ?? '');
    $code          = trim($_POST['code'] ?? '');
    $fee           = (float)($_POST['fee'] ?? 0);
    $is_manual_fee = isset($_POST['is_manual_fee']) ? 1 : 0;
    $status        = trim($_POST['status'] ?? 'active');
    $sort_order    = (int)($_POST['sort_order'] ?? 0);

    if ($label === '') {
        $error = 'Label is required.';
    } else {
        $code = makeCode($code !== '' ? $code : $label);

        if (!in_array($status, ['active', 'inactive'], true)) {
            $status = 'active';
        }

        try {
            $checkStmt = $pdo->prepare("SELECT id FROM sp_payment_types WHERE company_id = ? AND code = ? LIMIT 1");
            $checkStmt->execute([$companyId, $code]);

            if ($checkStmt->fetch()) {
                $error = 'Code already exists. Please use another code.';
            } else {
                $stmt = $pdo->prepare("
                    INSERT INTO sp_payment_types (company_id, code, label, fee, is_manual_fee, status, sort_order)
                    VALUES (?, ?, ?, ?, ?, ?, ?)
                ");
                $stmt->execute([$companyId, $code, $label, $fee, $is_manual_fee, $status, $sort_order]);
                $message = 'Payment type added successfully.';
            }
        } catch (Throwable $e) {
            $error = 'Error adding payment type: ' . $e->getMessage();
        }
    }
}

/*
|--------------------------------------------------------------------------
| Update Payment Type (scoped by company_id)
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_payment_type'])) {
    $id            = (int)($_POST['id'] ?? 0);
    $label         = trim($_POST['label'] ?? '');
    $code          = trim($_POST['code'] ?? '');
    $fee           = (float)($_POST['fee'] ?? 0);
    $is_manual_fee = isset($_POST['is_manual_fee']) ? 1 : 0;
    $status        = trim($_POST['status'] ?? 'active');
    $sort_order    = (int)($_POST['sort_order'] ?? 0);

    if ($id <= 0) {
        $error = 'Invalid payment type ID.';
    } elseif ($label === '') {
        $error = 'Label is required.';
    } else {
        $code = makeCode($code !== '' ? $code : $label);

        if (!in_array($status, ['active', 'inactive'], true)) {
            $status = 'active';
        }

        try {
            $checkStmt = $pdo->prepare("SELECT id FROM sp_payment_types WHERE company_id = ? AND code = ? AND id != ? LIMIT 1");
            $checkStmt->execute([$companyId, $code, $id]);

            if ($checkStmt->fetch()) {
                $error = 'Code already exists. Please use another code.';
            } else {
                $stmt = $pdo->prepare("
                    UPDATE sp_payment_types
                    SET code = ?, label = ?, fee = ?, is_manual_fee = ?, status = ?, sort_order = ?
                    WHERE id = ? AND company_id = ?
                ");
                $stmt->execute([$code, $label, $fee, $is_manual_fee, $status, $sort_order, $id, $companyId]);
                $message = 'Payment type updated successfully.';
            }
        } catch (Throwable $e) {
            $error = 'Error updating payment type: ' . $e->getMessage();
        }
    }
}

/*
|--------------------------------------------------------------------------
| Delete Payment Type (scoped by company_id)
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_payment_type'])) {
    $id = (int)($_POST['id'] ?? 0);

    if ($id <= 0) {
        $error = 'Invalid payment type ID.';
    } else {
        try {
            $stmt = $pdo->prepare("DELETE FROM sp_payment_types WHERE id = ? AND company_id = ?");
            $stmt->execute([$id, $companyId]);
            $message = 'Payment type deleted successfully.';
        } catch (Throwable $e) {
            $error = 'Error deleting payment type: ' . $e->getMessage();
        }
    }
}

/*
|--------------------------------------------------------------------------
| Load Payment Types (scoped by company_id)
|--------------------------------------------------------------------------
*/
$paymentTypes = [];
try {
    $ptStmt = $pdo->prepare("
        SELECT *
        FROM sp_payment_types
        WHERE company_id = ?
        ORDER BY sort_order ASC, id ASC
    ");
    $ptStmt->execute([$companyId]);
    $paymentTypes = $ptStmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $error = $error ?: ('Error loading payment types: ' . $e->getMessage());
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment Types</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Lao:wght@400;500;600;700&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --bg: #f3f6fb;
            --card: #ffffff;
            --ink: #111827;
            --muted: #64748b;
            --line: #eaeef5;
            --brand: #2563eb;
            --brand2: #1d4ed8;
            --shadow: 0 12px 30px rgba(30, 41, 59, 0.08);
            --shadow-sm: 0 2px 6px rgba(30, 41, 59, 0.06);
        }
        * { box-sizing: border-box; }
        body {
            margin: 0;
            font-family: 'Noto Sans Lao', 'Inter', Arial, sans-serif;
            background: var(--bg);
            color: var(--ink);
            -webkit-font-smoothing: antialiased;
        }
        .wrap { max-width: 1200px; margin: 0 auto; padding: 24px 16px 48px; }

        /* Dark top strip */
        .strip {
            background: #0f172a; color: #e2e8f0;
            border-radius: 16px; padding: 14px 20px; margin-bottom: 20px;
            display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap;
        }
        .strip .brand { font-weight: 800; letter-spacing: .3px; font-size: 16px; color: #fff; }
        .strip .company { color: #94a3b8; font-weight: 600; font-size: 14px; }

        /* Nav bar */
        .navbar { display: flex; gap: 10px; flex-wrap: wrap; margin-bottom: 22px; }
        .navbar a {
            background: #fff; border: 1px solid var(--line); padding: 9px 14px;
            border-radius: 999px; text-decoration: none; color: #475569; font-weight: 600;
            font-size: 14px; transition: all .15s ease; box-shadow: var(--shadow-sm);
        }
        .navbar a:hover { color: var(--brand); border-color: #bfdbfe; transform: translateY(-1px); }
        .navbar a.active { background: #eff6ff; border-color: #93c5fd; color: var(--brand); }
        .navbar a.logout { color: #b91c1c; }
        .navbar a.logout:hover { color: #991b1b; border-color: #fecaca; }

        .page-head { display: flex; align-items: center; justify-content: space-between; gap: 16px; flex-wrap: wrap; margin-bottom: 18px; }
        .page-head h1 { margin: 0; font-size: 26px; font-weight: 800; letter-spacing: -0.02em; }

        .card {
            background: var(--card); border: 1px solid var(--line); border-radius: 20px;
            box-shadow: var(--shadow); padding: 22px; margin-bottom: 20px;
        }
        .card h2 { margin-top: 0; font-size: 20px; font-weight: 700; }

        .message { background: #dcfce7; color: #166534; padding: 12px 14px; border-radius: 12px; margin-bottom: 14px; font-weight: 600; }
        .error   { background: #fee2e2; color: #991b1b; padding: 12px 14px; border-radius: 12px; margin-bottom: 14px; font-weight: 600; }

        .pt-grid {
            display: grid; grid-template-columns: 2fr 2fr 1fr 1fr 1fr auto auto;
            gap: 12px; align-items: end;
        }
        .pt-field label { font-weight: 600; display: block; margin-bottom: 6px; font-size: 13px; color: var(--muted); }
        .pt-field input, .pt-field select {
            width: 100%; padding: 10px 12px; border: 1px solid #e2e8f0; border-radius: 10px;
            font-size: 14px; font-family: inherit; background: #f8fafc;
        }
        .pt-field input:focus, .pt-field select:focus {
            outline: none; border-color: var(--brand); background: #fff;
            box-shadow: 0 0 0 4px rgba(37,99,235,0.12);
        }
        .pt-check { display: flex; align-items: center; gap: 8px; padding-bottom: 12px; }
        .pt-check input[type="checkbox"] { width: auto; margin: 0; }
        .pt-check label { margin: 0; font-size: 13px; font-weight: 600; color: var(--muted); }

        .btn {
            padding: 10px 16px; border: none; border-radius: 10px; cursor: pointer;
            font-weight: 700; font-size: 14px; font-family: inherit; transition: all .15s ease;
        }
        .btn-primary { background: var(--brand); color: #fff; }
        .btn-primary:hover { background: var(--brand2); transform: translateY(-1px); }
        .btn-danger { background: #dc2626; color: #fff; }
        .btn-danger:hover { background: #b91c1c; }
        .small { font-size: 12px; color: var(--muted); }

        .table-scroll { overflow-x: auto; border-radius: 14px; }
        table { width: 100%; border-collapse: collapse; min-width: 900px; }
        thead th {
            background: #f8fafc; color: var(--muted); text-transform: uppercase;
            font-size: 11px; letter-spacing: .05em; font-weight: 700;
            padding: 12px; text-align: left; border-bottom: 1px solid var(--line); white-space: nowrap;
        }
        tbody td { padding: 12px; border-bottom: 1px solid var(--line); text-align: left; font-size: 14px; vertical-align: middle; }
        tbody td input, tbody td select {
            width: 100%; padding: 8px 10px; border: 1px solid #e2e8f0; border-radius: 8px;
            font-size: 14px; font-family: inherit; background: #f8fafc;
        }
        td.num { text-align: center; width: 56px; color: var(--muted); font-weight: 600; }
        .actions { display: flex; gap: 8px; }
        .pt-inline { display: contents; }

        input[type="number"]::-webkit-outer-spin-button,
        input[type="number"]::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
        input[type="number"] { -moz-appearance: textfield; appearance: textfield; }

        @media (max-width: 900px) {
            .pt-grid { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>
    <div class="wrap">

        <div class="strip">
            <span class="brand">Seven Credit &middot; Job Management</span>
            <span class="company"><?= esc($companyName) ?></span>
        </div>

        <div class="navbar">
            <a href="sp_jobs_admin.php">Dashboard</a>
            <a href="sp_job_add.php">Open Job</a>
            <a href="../company/staff.php">Staff</a>
            <a href="sp_staff_payments.php">Staff Payment</a>
            <a href="sp_payment_types.php" class="active">Payment Types</a>
            <a href="dashboard.php">Back to Company</a>
            <a href="../auth/logout.php" class="logout">Logout</a>
        </div>

        <div class="page-head">
            <h1>Manage Payment Types</h1>
        </div>

        <?php if ($message): ?>
            <div class="message"><?= esc($message) ?></div>
        <?php endif; ?>
        <?php if ($error): ?>
            <div class="error"><?= esc($error) ?></div>
        <?php endif; ?>

        <div class="card">
            <h2>Add New Payment Type</h2>

            <form method="POST">
                <input type="hidden" name="add_payment_type" value="1">

                <div class="pt-grid">
                    <div class="pt-field">
                        <label>Label *</label>
                        <input type="text" name="label" placeholder="Setup new machine" required>
                    </div>

                    <div class="pt-field">
                        <label>Code</label>
                        <input type="text" name="code" placeholder="setup_new_machine">
                    </div>

                    <div class="pt-field">
                        <label>Fee</label>
                        <input type="number" step="1" min="0" name="fee" value="0">
                    </div>

                    <div class="pt-field">
                        <label>Status</label>
                        <select name="status">
                            <option value="active">Active</option>
                            <option value="inactive">Inactive</option>
                        </select>
                    </div>

                    <div class="pt-field">
                        <label>Sort Order</label>
                        <input type="number" step="1" name="sort_order" value="0">
                    </div>

                    <div class="pt-check">
                        <input type="checkbox" name="is_manual_fee" id="is_manual_fee_add">
                        <label for="is_manual_fee_add">Manual Fee</label>
                    </div>

                    <div>
                        <button type="submit" class="btn btn-primary">Add</button>
                    </div>
                </div>

                <p class="small" style="margin-top:12px;">
                    Example: Label = Setup new machine, Code = setup_new_machine, Fee = 20000
                </p>
            </form>
        </div>

        <div class="card">
            <h2>Existing Payment Types</h2>

            <?php if ($paymentTypes): ?>
                <div class="table-scroll">
                    <table>
                        <thead>
                            <tr>
                                <th class="num">ID</th>
                                <th>Label</th>
                                <th>Code</th>
                                <th>Fee</th>
                                <th>Manual Fee</th>
                                <th>Status</th>
                                <th>Sort Order</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($paymentTypes as $row): ?>
                                <tr>
                                    <form method="POST" class="pt-inline">
                                        <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">

                                        <td class="num"><?= (int)$row['id'] ?></td>

                                        <td>
                                            <input type="text" name="label" value="<?= esc($row['label']) ?>" required>
                                        </td>

                                        <td>
                                            <input type="text" name="code" value="<?= esc($row['code']) ?>" required>
                                        </td>

                                        <td>
                                            <input type="number" step="1" min="0" name="fee" value="<?= esc(number_format((float)$row['fee'], 0, '.', '')) ?>">
                                        </td>

                                        <td>
                                            <input type="checkbox" name="is_manual_fee" value="1" <?= !empty($row['is_manual_fee']) ? 'checked' : '' ?>>
                                        </td>

                                        <td>
                                            <select name="status">
                                                <option value="active"   <?= ($row['status'] ?? '') === 'active'   ? 'selected' : '' ?>>Active</option>
                                                <option value="inactive" <?= ($row['status'] ?? '') === 'inactive' ? 'selected' : '' ?>>Inactive</option>
                                            </select>
                                        </td>

                                        <td>
                                            <input type="number" step="1" name="sort_order" value="<?= (int)$row['sort_order'] ?>">
                                        </td>

                                        <td>
                                            <div class="actions">
                                                <button type="submit" name="update_payment_type" value="1" class="btn btn-primary">Save</button>
                                                <button type="submit" name="delete_payment_type" value="1" class="btn btn-danger" onclick="return confirm('Delete this payment type?')">Delete</button>
                                            </div>
                                        </td>
                                    </form>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <p class="small">No payment types found.</p>
            <?php endif; ?>
        </div>

    </div>
</body>
</html>
<?php ob_end_flush(); ?>