<?php
session_start();

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

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

$id = isset($_GET["id"]) ? (int)$_GET["id"] : 0;

/* load company */
$company = null;
if ($id > 0) {
    $st = $pdo->prepare("SELECT * FROM companies WHERE id = ?");
    $st->execute([$id]);
    $company = $st->fetch(PDO::FETCH_ASSOC);
}

if (!$company) { header("Location: companies.php"); exit; }

$errors  = [];
$success = "";

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $amount = (float)str_replace(",", "", $_POST["amount"] ?? "0");
    $note   = trim($_POST["note"] ?? "");

    if ($amount <= 0)   $errors[] = "Amount must be greater than 0.";
    if ($amount > 1e10) $errors[] = "Amount too large.";

    if (empty($errors)) {
        $pdo->beginTransaction();
        try {
            /* Add credit to company */
            $pdo->prepare("UPDATE companies SET credit_balance = credit_balance + ? WHERE id = ?")
                ->execute([$amount, $id]);

            /* Log the transfer */
            $pdo->prepare("
                INSERT INTO company_credit_transfers
                    (company_id, amount, note, transferred_by, created_at)
                VALUES (?, ?, ?, ?, NOW())
            ")->execute([$id, $amount, $note, $_SESSION["user_id"]]);

            $pdo->commit();

            /* Reload company balance */
            $st = $pdo->prepare("SELECT * FROM companies WHERE id = ?");
            $st->execute([$id]);
            $company = $st->fetch(PDO::FETCH_ASSOC);

            $success = number_format($amount, 0) . " credit transferred successfully.";
        } catch (Throwable $e) {
            $pdo->rollBack();
            $errors[] = "Database error: " . $e->getMessage();
        }
    }
}

/* Transfer history */
$history = $pdo->prepare("
    SELECT t.*, u.name AS transferred_by_name
    FROM company_credit_transfers t
    JOIN users u ON u.id = t.transferred_by
    WHERE t.company_id = ?
    ORDER BY t.created_at DESC
    LIMIT 50
");
$history->execute([$id]);
$history = $history->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="lo">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Credit Transfer — <?= htmlspecialchars($company["name"]) ?></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; --green: #16a34a; --green-lt: #dcfce7;
            --red: #dc2626; --red-lt: #fee2e2;
            --surface: #ffffff; --bg: #f0f4f8; --border: #e2e8f0;
            --text: #0f172a; --muted: #64748b;
            --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; }

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

        /* balance banner */
        .balance-banner {
            background: linear-gradient(135deg,#0f2444,#2563eb);
            border-radius: 16px; padding: 24px 28px; color: #fff;
            display: flex; align-items: center; justify-content: space-between;
            gap: 16px; margin-bottom: 24px;
            box-shadow: 0 6px 24px rgba(15,23,42,.18);
        }
        .balance-banner .co-name { font-size: 18px; font-weight: 800; }
        .balance-banner .co-sub  { font-size: 12px; color: rgba(255,255,255,.7); margin-top: 4px; }
        .balance-right { text-align: right; }
        .balance-right .lbl { font-size: 12px; color: rgba(255,255,255,.7); text-transform: uppercase; letter-spacing: .5px; }
        .balance-right .val { font-size: 30px; font-weight: 800; margin-top: 4px; }

        .two-col { display: grid; grid-template-columns: 1fr 1.4fr; gap: 20px; align-items: start; }

        /* form card */
        .form-card { background: var(--surface); border-radius: var(--radius); box-shadow: var(--shadow); border: 1px solid var(--border); padding: 26px; }
        .card-title { font-size: 14px; font-weight: 800; color: var(--text); margin-bottom: 20px; padding-bottom: 12px; border-bottom: 1px solid var(--border); }

        .form-group { margin-bottom: 16px; }
        label { display: block; font-size: 13px; font-weight: 700; color: var(--text); margin-bottom: 6px; }
        input[type="text"], input[type="number"], 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; outline: none;
        }
        input:focus, textarea:focus { border-color: var(--primary); background: #fff; }

        /* quick amounts */
        .quick-amounts { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 14px; }
        .quick-btn { padding: 6px 14px; border-radius: 8px; border: 1.5px solid var(--border); background: var(--surface); font-size: 12px; font-weight: 700; color: var(--muted); cursor: pointer; font-family: inherit; transition: all .15s; }
        .quick-btn:hover { border-color: var(--primary); color: var(--primary); background: #eff6ff; }

        .btn { display: inline-flex; align-items: center; gap: 7px; padding: 11px 22px; border-radius: 10px; font-size: 14px; font-weight: 700; font-family: inherit; cursor: pointer; border: none; transition: all .15s; width: 100%; justify-content: center; }
        .btn-success { background: linear-gradient(135deg,#14532d,#16a34a); color: #fff; box-shadow: 0 3px 10px rgba(22,163,74,.3); margin-top: 4px; }
        .btn-success:hover { opacity: .9; }

        .alert { padding: 12px 16px; border-radius: 10px; margin-bottom: 16px; font-size: 13px; font-weight: 600; }
        .alert-success { background: var(--green-lt); color: var(--green); border: 1.5px solid #86efac; }
        .alert-danger  { background: var(--red-lt);   color: var(--red);   border: 1.5px solid #fca5a5; }

        /* history table */
        .table-card { background: var(--surface); border-radius: var(--radius); box-shadow: var(--shadow); border: 1px solid var(--border); overflow: hidden; }
        .table-card .card-title { padding: 16px 20px 12px; margin-bottom: 0; border-bottom: 1px solid var(--border); }
        table { width: 100%; border-collapse: collapse; }
        thead th { background: #f8fafc; padding: 10px 16px; text-align: left; font-size: 11px; font-weight: 700; color: var(--muted); text-transform: uppercase; letter-spacing: .5px; border-bottom: 1px solid var(--border); }
        tbody tr { border-bottom: 1px solid var(--border); }
        tbody tr:last-child { border-bottom: none; }
        tbody tr:hover { background: #f8fafc; }
        td { padding: 12px 16px; font-size: 13px; vertical-align: middle; }

        .amount-cell { font-weight: 800; color: var(--green); font-size: 14px; }

        @media (max-width: 700px) { .two-col { grid-template-columns: 1fr; } .page-body { padding: 16px; } .top-bar { padding: 10px 16px; } }
    </style>
</head>
<body>

<div class="top-bar">
    <a class="back-link" href="companies.php">← Companies</a>
    <h1>💰 Transfer Credit to Company</h1>
</div>

<div class="page-body">

    <!-- Balance banner -->
    <div class="balance-banner">
        <div>
            <div class="co-name">🏢 <?= htmlspecialchars($company["name"]) ?></div>
            <div class="co-sub">Company ID: <?= $company["id"] ?> &nbsp;·&nbsp; Status: <?= ucfirst($company["status"]) ?></div>
        </div>
        <div class="balance-right">
            <div class="lbl">Current Credit Balance</div>
            <div class="val">₭ <?= number_format((float)$company["credit_balance"], 0) ?></div>
        </div>
    </div>

    <div class="two-col">

        <!-- Transfer form -->
        <div class="form-card">
            <div class="card-title">💸 Send Credit</div>

            <?php if ($success): ?>
                <div class="alert alert-success">✅ <?= htmlspecialchars($success) ?></div>
            <?php endif; ?>

            <?php if (!empty($errors)): ?>
                <div class="alert alert-danger">
                    <?php foreach ($errors as $e): ?>⚠️ <?= htmlspecialchars($e) ?><br><?php endforeach; ?>
                </div>
            <?php endif; ?>

            <form method="POST">

                <div class="form-group">
                    <label>Quick amounts</label>
                    <div class="quick-amounts">
                        <?php foreach ([100000,500000,1000000,5000000,10000000] as $q): ?>
                            <button type="button" class="quick-btn"
                                onclick="document.getElementById('amount').value = '<?= $q ?>'">
                                ₭ <?= number_format($q) ?>
                            </button>
                        <?php endforeach; ?>
                    </div>
                </div>

                <div class="form-group">
                    <label for="amount">Amount (₭) <span style="color:var(--red)">*</span></label>
                    <input type="number" id="amount" name="amount" min="1" step="1"
                        value="<?= htmlspecialchars($_POST["amount"] ?? "") ?>"
                        placeholder="e.g. 1000000" required>
                </div>

                <div class="form-group">
                    <label for="note">Note <span style="color:var(--muted);font-weight:400;font-size:12px;">(optional)</span></label>
                    <textarea id="note" name="note" rows="2"
                        placeholder="e.g. Monthly credit allocation"><?= htmlspecialchars($_POST["note"] ?? "") ?></textarea>
                </div>

                <button class="btn btn-success" type="submit">
                    💰 Transfer Credit Now
                </button>
            </form>
        </div>

        <!-- History -->
        <div>
            <div class="table-card">
                <div class="card-title" style="padding:16px 20px 12px;">📋 Transfer History</div>
                <table>
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Amount</th>
                            <th>By</th>
                            <th>Note</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php if (empty($history)): ?>
                        <tr><td colspan="4" style="text-align:center;color:var(--muted);padding:30px;">No transfers yet.</td></tr>
                    <?php else: ?>
                        <?php foreach ($history as $h): ?>
                        <tr>
                            <td style="color:var(--muted);font-size:12px;">
                                <?= date("d M Y H:i", strtotime($h["created_at"])) ?>
                            </td>
                            <td class="amount-cell">₭ <?= number_format((float)$h["amount"], 0) ?></td>
                            <td><?= htmlspecialchars($h["transferred_by_name"]) ?></td>
                            <td style="color:var(--muted);font-size:12px;">
                                <?= htmlspecialchars($h["note"] ?: "—") ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

    </div>
</div>
</body>
</html>