<?php
session_start();

if (!isset($_SESSION["user_id"]) || $_SESSION["role"] !== "admin") {
    header("Location: ../auth/login.php");
    exit;
}

require_once '../config/database.php';
require_once '../config/modules.php';

$id      = isset($_GET["id"]) ? (int)$_GET["id"] : 0;
$isEdit  = $id > 0;
$company = ["name" => "", "status" => "active", "logo" => ""];
$errors  = [];
$enabledModules = [];

if ($isEdit) {
    $row = $pdo->prepare("SELECT * FROM companies WHERE id = ?");
    $row->execute([$id]);
    $company = $row->fetch(PDO::FETCH_ASSOC);
    if (!$company) { header("Location: companies.php"); exit; }
    $enabledModules = company_enabled_modules($pdo, $id);
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $name   = trim($_POST["name"] ?? "");
    $status = $_POST["status"] === "inactive" ? "inactive" : "active";

    if ($name === "") $errors[] = "Company name is required.";

    /* ── Create company admin user ── */
    $adminName  = trim($_POST["admin_name"]  ?? "");
    $adminEmail = trim($_POST["admin_email"] ?? "");
    $adminPass  = $_POST["admin_password"]   ?? "";

    if (!$isEdit) {
        if ($adminName  === "") $errors[] = "Admin name is required.";
        if ($adminEmail === "") $errors[] = "Admin email is required.";
        if (strlen($adminPass) < 6) $errors[] = "Admin password must be at least 6 characters.";

        if (empty($errors)) {
            /* check email unique */
            $chk = $pdo->prepare("SELECT id FROM users WHERE email = ?");
            $chk->execute([$adminEmail]);
            if ($chk->fetch()) $errors[] = "Email $adminEmail is already registered.";
        }
    }

    /* selected modules (also used to repopulate on error) */
    $selModules = array_values(array_intersect(array_keys(available_modules()), (array)($_POST["modules"] ?? [])));
    $enabledModules = $selModules;

    if (empty($errors)) {
        $pdo->beginTransaction();
        try {
            $cid = $id;
            if ($isEdit) {
                $pdo->prepare("UPDATE companies SET name=?, status=? WHERE id=?")
                    ->execute([$name, $status, $id]);
            } else {
                /* Insert company */
                $pdo->prepare("INSERT INTO companies (name, status, credit_balance, created_at) VALUES (?,?,0,NOW())")
                    ->execute([$name, $status]);
                $newCompanyId = (int)$pdo->lastInsertId();
                $cid = $newCompanyId;

                /* Insert company_admin user */
                $hash = password_hash($adminPass, PASSWORD_DEFAULT);
                $pdo->prepare("INSERT INTO users (name, email, password, role, status, created_at) VALUES (?,?,?,'company_admin','active',NOW())")
                    ->execute([$adminName, $adminEmail, $hash]);
                $newUserId = (int)$pdo->lastInsertId();

                /* Link to company_staff */
                $pdo->prepare("INSERT INTO company_staff (user_id, company_id, staff_role, joined_date) VALUES (?,?,'admin',CURDATE())")
                    ->execute([$newUserId, $newCompanyId]);

                /* Auto-create customer wallet for company admin
                   so they can use the customer dashboard (wallet + HR) */
                $customerCode = "CA" . str_pad($newCompanyId, 3, "0", STR_PAD_LEFT) . str_pad($newUserId, 4, "0", STR_PAD_LEFT);
                $pdo->prepare("INSERT INTO customers (user_id, customer_code, full_name, balance, created_at) VALUES (?,?,?,0,NOW())")
                    ->execute([$newUserId, $customerCode, $adminName]);
            }

            /* sync enabled modules */
            $pdo->prepare("DELETE FROM company_modules WHERE company_id=?")->execute([$cid]);
            if (!empty($selModules)) {
                $insM = $pdo->prepare("INSERT INTO company_modules (company_id, module_key) VALUES (?,?)");
                foreach ($selModules as $mk) $insM->execute([$cid, $mk]);
            }

            $pdo->commit();
            header("Location: companies.php?msg=saved");
            exit;
        } catch (Throwable $e) {
            $pdo->rollBack();
            $errors[] = "Database error: " . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="lo">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $isEdit ? "Edit" : "Add" ?> Company — Admin</title>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Lao:wght@400;600;700;800&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
        :root {
            --primary: #2563eb; --surface: #ffffff; --bg: #f0f4f8;
            --border: #e2e8f0; --text: #0f172a; --muted: #64748b;
            --red: #dc2626; --red-lt: #fee2e2; --green: #16a34a; --green-lt: #dcfce7;
            --radius: 14px; --shadow: 0 2px 14px rgba(15,23,42,.09);
        }
        body { font-family: "Noto Sans Lao","Inter",Arial,sans-serif; background: var(--bg); color: var(--text); min-height: 100vh; }

        .top-bar { background: var(--surface); border-bottom: 1px solid var(--border); padding: 12px 32px; display: flex; align-items: center; gap: 16px; position: sticky; top: 0; z-index: 100; box-shadow: 0 1px 6px rgba(15,23,42,.06); }
        .back-link { display: inline-flex; align-items: center; gap: 6px; color: var(--muted); text-decoration: none; font-size: 13px; font-weight: 600; padding: 6px 12px; border-radius: 8px; border: 1.5px solid var(--border); transition: all .15s; }
        .back-link:hover { border-color: var(--primary); color: var(--primary); }
        .top-bar h1 { font-size: 17px; font-weight: 800; color: var(--text); }

        .page-body { padding: 32px; max-width: 680px; margin: auto; }

        .form-card { background: var(--surface); border-radius: var(--radius); box-shadow: var(--shadow); border: 1px solid var(--border); padding: 32px; }

        .section-head { font-size: 13px; font-weight: 700; color: var(--muted); text-transform: uppercase; letter-spacing: .5px; margin: 24px 0 14px; padding-bottom: 8px; border-bottom: 1px solid var(--border); }
        .section-head:first-child { margin-top: 0; }

        .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
        .form-group { margin-bottom: 18px; }
        label { display: block; font-size: 13px; font-weight: 700; color: var(--text); margin-bottom: 6px; }
        .label-hint { font-weight: 400; color: var(--muted); font-size: 12px; }
        input[type="text"], input[type="email"], input[type="password"], select, textarea {
            width: 100%; padding: 11px 14px; border: 1.5px solid var(--border); border-radius: 10px;
            font-size: 14px; font-family: inherit; color: var(--text); background: #f8fafc;
            transition: border-color .15s, box-shadow .15s; outline: none;
        }
        input:focus, select:focus, textarea:focus { border-color: var(--primary); box-shadow: 0 0 0 3px rgba(37,99,235,.1); background: #fff; }

        .error-list { background: var(--red-lt); border: 1.5px solid #fca5a5; border-radius: 10px; padding: 14px 16px; margin-bottom: 22px; }
        .error-list p { color: var(--red); font-size: 13px; font-weight: 600; margin-bottom: 6px; }
        .error-list ul { padding-left: 18px; }
        .error-list li { color: var(--red); font-size: 13px; margin-bottom: 3px; }

        .info-box { background: #eff6ff; border: 1.5px solid #93c5fd; border-radius: 10px; padding: 12px 16px; margin-bottom: 22px; font-size: 13px; color: #1e40af; line-height: 1.6; }

        .form-actions { display: flex; gap: 10px; justify-content: flex-end; margin-top: 24px; padding-top: 20px; border-top: 1px solid var(--border); }
        .btn { display: inline-flex; align-items: center; gap: 7px; padding: 10px 22px; border-radius: 10px; font-size: 14px; font-weight: 700; font-family: inherit; cursor: pointer; border: none; text-decoration: none; transition: all .15s; }
        .btn-primary { background: linear-gradient(135deg,#1e3a5f,#2563eb); color: #fff; box-shadow: 0 3px 10px rgba(37,99,235,.3); }
        .btn-primary:hover { opacity: .9; }
        .btn-cancel { background: #f1f5f9; color: var(--muted); border: 1.5px solid var(--border); }
        .btn-cancel:hover { background: var(--border); }

        .mod-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
        .mod-card { display: flex; align-items: flex-start; gap: 11px; padding: 14px; border: 1.5px solid var(--border); border-radius: 12px; cursor: pointer; background: #f8fafc; transition: border-color .15s, background .15s; }
        .mod-card:has(input:checked) { border-color: var(--primary); background: #eff6ff; }
        .mod-card input { width: 18px; height: 18px; margin-top: 2px; flex-shrink: 0; cursor: pointer; }
        .mod-ic { font-size: 22px; line-height: 1; }
        .mod-txt { display: flex; flex-direction: column; gap: 2px; }
        .mod-name { font-size: 14px; font-weight: 700; color: var(--text); }
        .mod-desc { font-size: 12px; color: var(--muted); line-height: 1.4; }
        @media (max-width: 600px) { .form-row { grid-template-columns: 1fr; } .mod-grid { grid-template-columns: 1fr; } .page-body { padding: 16px; } .form-card { padding: 20px; } }
    </style>
</head>
<body>

<div class="top-bar">
    <a class="back-link" href="companies.php">← Companies</a>
    <h1><?= $isEdit ? "✏️ Edit Company" : "🏢 Add New Company" ?></h1>
</div>

<div class="page-body">
    <div class="form-card">

        <?php if (!empty($errors)): ?>
        <div class="error-list">
            <p>⚠️ Please fix the following:</p>
            <ul><?php foreach ($errors as $e): ?><li><?= htmlspecialchars($e) ?></li><?php endforeach; ?></ul>
        </div>
        <?php endif; ?>

        <form method="POST">

            <!-- Company info -->
            <div class="section-head">Company Information</div>

            <div class="form-group">
                <label for="name">Company Name <span style="color:var(--red)">*</span></label>
                <input type="text" id="name" name="name"
                    value="<?= htmlspecialchars($_POST["name"] ?? $company["name"]) ?>"
                    placeholder="e.g. Seven Digital Co., Ltd." required>
            </div>

            <div class="form-group">
                <label for="status">Status</label>
                <select id="status" name="status">
                    <option value="active"   <?= ($company["status"] ?? "active") === "active"   ? "selected" : "" ?>>✅ Active</option>
                    <option value="inactive" <?= ($company["status"] ?? "active") === "inactive" ? "selected" : "" ?>>⛔ Inactive</option>
                </select>
            </div>

            <?php if (!$isEdit): ?>
            <!-- Company admin account -->
            <div class="section-head">Company Admin Account</div>

            <div class="info-box">
                ℹ️ A <strong>company_admin</strong> account will be created automatically and linked to this company. The admin can then log in and manage their own staff.
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label for="admin_name">Admin Full Name <span style="color:var(--red)">*</span></label>
                    <input type="text" id="admin_name" name="admin_name"
                        value="<?= htmlspecialchars($_POST["admin_name"] ?? "") ?>"
                        placeholder="e.g. Somchai Phommasack">
                </div>
                <div class="form-group">
                    <label for="admin_email">Admin Email <span style="color:var(--red)">*</span></label>
                    <input type="email" id="admin_email" name="admin_email"
                        value="<?= htmlspecialchars($_POST["admin_email"] ?? "") ?>"
                        placeholder="admin@company.com">
                </div>
            </div>

            <div class="form-group">
                <label for="admin_password">
                    Admin Password <span style="color:var(--red)">*</span>
                    <span class="label-hint">(min 6 characters)</span>
                </label>
                <input type="password" id="admin_password" name="admin_password" placeholder="••••••••">
            </div>
            <?php endif; ?>

            <!-- Modules / functions -->
            <div class="section-head">Modules / Functions</div>
            <div class="info-box">
                ✅ Tick the functions this company will use. They appear on the company's dashboard. You can change these anytime by editing the company.
            </div>
            <div class="mod-grid">
                <?php foreach (available_modules() as $key => $m): ?>
                <label class="mod-card">
                    <input type="checkbox" name="modules[]" value="<?= $key ?>" <?= in_array($key, $enabledModules) ? 'checked' : '' ?>>
                    <span class="mod-ic"><?= $m['icon'] ?></span>
                    <span class="mod-txt">
                        <span class="mod-name"><?= htmlspecialchars($m['en']) ?></span>
                        <span class="mod-desc"><?= htmlspecialchars($m['desc_en']) ?></span>
                    </span>
                </label>
                <?php endforeach; ?>
            </div>

            <div class="form-actions">
                <a class="btn btn-cancel" href="companies.php">Cancel</a>
                <button class="btn btn-primary" type="submit">
                    <?= $isEdit ? "💾 Save Changes" : "🏢 Create Company" ?>
                </button>
            </div>

        </form>
    </div>
</div>
<?php require __DIR__ . '/../config/auto_update.php'; ?>
</body>
</html>