<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

$pageTitle = 'POS Machines';

if (!function_exists('h')) {
    function h($value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('fetch_bank_accounts')) {
    function fetch_bank_accounts(PDO $pdo): array
    {
        try {
            $stmt = $pdo->query("\n                SELECT\n                    b.ID,\n                    b.AccountName,\n                    b.Bank,\n                    b.Branch,\n                    b.AccountNo,\n                    b.Currency,\n                    cur.CurrencyCode,\n                    p.name AS property_name\n                FROM tblbankdetails b\n                LEFT JOIN tblcurrency cur ON cur.CurrencyID = b.Currency\n                LEFT JOIN properties p ON p.id = b.property_id\n                WHERE b.bank_status = 1\n                ORDER BY b.Bank ASC, b.AccountName ASC, b.AccountNo ASC\n            ");
            return $stmt ? $stmt->fetchAll(PDO::FETCH_ASSOC) : [];
        } catch (Throwable $e) {
            return [];
        }
    }
}

if (!function_exists('bank_label')) {
    function bank_label(array $row): string
    {
        $parts = [];
        $parts[] = trim((string)($row['Bank'] ?? ''));
        $parts[] = trim((string)($row['AccountName'] ?? ''));
        if (!empty($row['AccountNo'])) {
            $parts[] = 'Acct: ' . trim((string)$row['AccountNo']);
        }
        if (!empty($row['CurrencyCode'])) {
            $parts[] = trim((string)$row['CurrencyCode']);
        }
        if (!empty($row['property_name'])) {
            $parts[] = trim((string)$row['property_name']);
        }
        return implode(' | ', array_filter($parts, static fn($v) => $v !== ''));
    }
}

$form = [
    'id' => 0,
    'bank_detail_id' => '',
    'machine_name' => '',
    'terminal_id' => '',
    'merchant_id' => '',
    'serial_no' => '',
    'provider' => '',
    'location' => '',
    'settlement_days' => '1',
    'commission_percent' => '0.00',
    'notes' => '',
    'status' => '1',
];

$errors = [];
$success = '';
$editing = false;

if (isset($_GET['saved']) && (int)$_GET['saved'] === 1) {
    $success = 'POS machine saved successfully.';
}
if (isset($_GET['deleted']) && (int)$_GET['deleted'] === 1) {
    $success = 'POS machine deleted successfully.';
}

$bankAccounts = fetch_bank_accounts($pdo);
$bankMap = [];
foreach ($bankAccounts as $bank) {
    $bankMap[(string)$bank['ID']] = bank_label($bank);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_pos_machine'])) {
    $form['id'] = (int)($_POST['id'] ?? 0);
    $form['bank_detail_id'] = trim((string)($_POST['bank_detail_id'] ?? ''));
    $form['machine_name'] = trim((string)($_POST['machine_name'] ?? ''));
    $form['terminal_id'] = trim((string)($_POST['terminal_id'] ?? ''));
    $form['merchant_id'] = trim((string)($_POST['merchant_id'] ?? ''));
    $form['serial_no'] = trim((string)($_POST['serial_no'] ?? ''));
    $form['provider'] = trim((string)($_POST['provider'] ?? ''));
    $form['location'] = trim((string)($_POST['location'] ?? ''));
    $form['settlement_days'] = (string)max(0, (int)($_POST['settlement_days'] ?? 1));
    $form['commission_percent'] = number_format((float)($_POST['commission_percent'] ?? 0), 2, '.', '');
    $form['notes'] = trim((string)($_POST['notes'] ?? ''));
    $form['status'] = (string)((int)($_POST['status'] ?? 1));

    $editing = $form['id'] > 0;

    if ($form['bank_detail_id'] === '' || (int)$form['bank_detail_id'] <= 0) {
        $errors[] = 'Bank account is required.';
    }
    if ($form['machine_name'] === '') {
        $errors[] = 'Machine name is required.';
    }
    if ($form['terminal_id'] === '') {
        $errors[] = 'Terminal ID is required.';
    }
    if ((float)$form['commission_percent'] < 0) {
        $errors[] = 'Commission percent cannot be negative.';
    }

    if (!$errors) {
        try {
            $stmt = $pdo->prepare("\n                SELECT id\n                FROM pos_machines\n                WHERE terminal_id = :terminal_id\n                  AND id <> :id\n                LIMIT 1\n            ");
            $stmt->execute([
                ':terminal_id' => $form['terminal_id'],
                ':id' => (int)$form['id'],
            ]);
            if ($stmt->fetch(PDO::FETCH_ASSOC)) {
                $errors[] = 'Another POS machine already uses this Terminal ID.';
            }
        } catch (Throwable $e) {
            $errors[] = $e->getMessage();
        }
    }

    if (!$errors) {
        try {
            if ($editing) {
                $stmt = $pdo->prepare("\n                    UPDATE pos_machines\n                    SET bank_detail_id = :bank_detail_id,\n                        machine_name = :machine_name,\n                        terminal_id = :terminal_id,\n                        merchant_id = :merchant_id,\n                        serial_no = :serial_no,\n                        provider = :provider,\n                        location = :location,\n                        settlement_days = :settlement_days,\n                        commission_percent = :commission_percent,\n                        notes = :notes,\n                        status = :status,\n                        updated_at = NOW()\n                    WHERE id = :id\n                ");
                $stmt->execute([
                    ':bank_detail_id' => (int)$form['bank_detail_id'],
                    ':machine_name' => $form['machine_name'],
                    ':terminal_id' => $form['terminal_id'],
                    ':merchant_id' => $form['merchant_id'] !== '' ? $form['merchant_id'] : null,
                    ':serial_no' => $form['serial_no'] !== '' ? $form['serial_no'] : null,
                    ':provider' => $form['provider'] !== '' ? $form['provider'] : null,
                    ':location' => $form['location'] !== '' ? $form['location'] : null,
                    ':settlement_days' => (int)$form['settlement_days'],
                    ':commission_percent' => (float)$form['commission_percent'],
                    ':notes' => $form['notes'] !== '' ? $form['notes'] : null,
                    ':status' => (int)$form['status'],
                    ':id' => (int)$form['id'],
                ]);
            } else {
                $stmt = $pdo->prepare("\n                    INSERT INTO pos_machines\n                    (\n                        bank_detail_id, machine_name, terminal_id, merchant_id, serial_no,\n                        provider, location, settlement_days, commission_percent, notes,\n                        status, created_at, updated_at\n                    )\n                    VALUES\n                    (\n                        :bank_detail_id, :machine_name, :terminal_id, :merchant_id, :serial_no,\n                        :provider, :location, :settlement_days, :commission_percent, :notes,\n                        :status, NOW(), NOW()\n                    )\n                ");
                $stmt->execute([
                    ':bank_detail_id' => (int)$form['bank_detail_id'],
                    ':machine_name' => $form['machine_name'],
                    ':terminal_id' => $form['terminal_id'],
                    ':merchant_id' => $form['merchant_id'] !== '' ? $form['merchant_id'] : null,
                    ':serial_no' => $form['serial_no'] !== '' ? $form['serial_no'] : null,
                    ':provider' => $form['provider'] !== '' ? $form['provider'] : null,
                    ':location' => $form['location'] !== '' ? $form['location'] : null,
                    ':settlement_days' => (int)$form['settlement_days'],
                    ':commission_percent' => (float)$form['commission_percent'],
                    ':notes' => $form['notes'] !== '' ? $form['notes'] : null,
                    ':status' => (int)$form['status'],
                ]);
            }

            header('Location: pos_machines.php?saved=1');
            exit;
        } catch (Throwable $e) {
            $errors[] = $e->getMessage();
        }
    }
}

if (isset($_GET['delete']) && (int)$_GET['delete'] > 0) {
    try {
        $stmt = $pdo->prepare("DELETE FROM pos_machines WHERE id = :id");
        $stmt->execute([':id' => (int)$_GET['delete']]);
        header('Location: pos_machines.php?deleted=1');
        exit;
    } catch (Throwable $e) {
        $errors[] = $e->getMessage();
    }
}

if (isset($_GET['edit']) && (int)$_GET['edit'] > 0) {
    try {
        $stmt = $pdo->prepare("SELECT * FROM pos_machines WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => (int)$_GET['edit']]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($row) {
            $editing = true;
            $form = [
                'id' => (int)$row['id'],
                'bank_detail_id' => (string)$row['bank_detail_id'],
                'machine_name' => (string)$row['machine_name'],
                'terminal_id' => (string)$row['terminal_id'],
                'merchant_id' => (string)($row['merchant_id'] ?? ''),
                'serial_no' => (string)($row['serial_no'] ?? ''),
                'provider' => (string)($row['provider'] ?? ''),
                'location' => (string)($row['location'] ?? ''),
                'settlement_days' => (string)(int)($row['settlement_days'] ?? 1),
                'commission_percent' => number_format((float)($row['commission_percent'] ?? 0), 2, '.', ''),
                'notes' => (string)($row['notes'] ?? ''),
                'status' => (string)(int)($row['status'] ?? 1),
            ];
        } else {
            $errors[] = 'POS machine not found.';
        }
    } catch (Throwable $e) {
        $errors[] = $e->getMessage();
    }
}

$search = trim((string)($_GET['q'] ?? ''));
$statusFilter = trim((string)($_GET['status'] ?? ''));

$sql = "\n    SELECT\n        pm.*,\n        b.AccountName,\n        b.Bank,\n        b.Branch,\n        b.AccountNo,\n        cur.CurrencyCode,\n        p.name AS property_name\n    FROM pos_machines pm\n    INNER JOIN tblbankdetails b ON b.ID = pm.bank_detail_id\n    LEFT JOIN tblcurrency cur ON cur.CurrencyID = b.Currency\n    LEFT JOIN properties p ON p.id = b.property_id\n    WHERE 1=1\n";
$params = [];

if ($search !== '') {
    $sql .= "\n        AND (\n            pm.machine_name LIKE :search\n            OR pm.terminal_id LIKE :search\n            OR pm.merchant_id LIKE :search\n            OR pm.serial_no LIKE :search\n            OR pm.provider LIKE :search\n            OR pm.location LIKE :search\n            OR b.AccountName LIKE :search\n            OR b.Bank LIKE :search\n            OR b.AccountNo LIKE :search\n            OR p.name LIKE :search\n        )\n    ";
    $params[':search'] = '%' . $search . '%';
}

if ($statusFilter !== '' && in_array($statusFilter, ['0', '1'], true)) {
    $sql .= " AND pm.status = :status ";
    $params[':status'] = (int)$statusFilter;
}

$sql .= " ORDER BY pm.status DESC, pm.machine_name ASC, pm.terminal_id ASC ";

try {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $machines = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $machines = [];
    $errors[] = $e->getMessage();
}

require_once __DIR__ . '/../../includes/header.php';
?>

<style>
.pos-hero {
    background: linear-gradient(135deg, #2f343a, #5c636b);
    color: #fff;
    border-radius: 18px;
    padding: 18px 22px;
    margin-bottom: 18px;
    box-shadow: 0 10px 26px rgba(15, 23, 42, .12);
}
.pos-hero-title {
    font-size: 1.45rem;
    font-weight: 800;
    letter-spacing: -.02em;
}
.pos-hero-subtitle {
    color: rgba(255,255,255,.78);
    font-size: .92rem;
}
.form-section, .panel-card {
    border: 1px solid #e5e7eb;
    border-radius: 18px;
    background: #fff;
    box-shadow: 0 10px 24px rgba(15, 23, 42, .06);
}
.form-section { padding: 18px; }
.form-section-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 800;
    font-size: 1rem;
    margin-bottom: 14px;
    color: #1f2937;
}
.table-modern thead th {
    position: sticky;
    top: 0;
    background: #f8fafc;
    z-index: 2;
    font-size: .78rem;
    text-transform: uppercase;
    letter-spacing: .04em;
    color: #475569;
    border-bottom: 1px solid #e5e7eb;
}
.table-modern td {
    vertical-align: middle;
    font-size: .92rem;
}
.pos-table-wrap {
    max-height: 640px;
    overflow: auto;
}
.small-muted {
    color: #64748b;
    font-size: .78rem;
}
.bank-select-note {
    font-size: .76rem;
    color: #64748b;
    margin-top: 4px;
}
</style>

<div class="pos-hero">
    <div class="row align-items-center g-3">
        <div class="col-lg-8">
            <div class="small text-white-50"><i class="bi bi-credit-card-2-front me-1"></i> Setup</div>
            <div class="pos-hero-title">POS Machines</div>
            <div class="pos-hero-subtitle">Register POS terminals and link each machine to the correct bank account for settlement and reconciliation.</div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="pos_machines.php" class="btn btn-outline-light">
                <i class="bi bi-plus-circle me-2"></i>New POS Machine
            </a>
        </div>
    </div>
</div>

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

<?php if ($errors): ?>
    <div class="alert alert-danger">
        <div class="fw-bold mb-2">Please fix the following:</div>
        <ul class="mb-0">
            <?php foreach ($errors as $err): ?>
                <li><?php echo h($err); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<div class="row g-4">
    <div class="col-xl-5">
        <div class="form-section">
            <div class="form-section-title">
                <i class="bi bi-credit-card"></i>
                <?php echo $editing ? 'Edit POS Machine' : 'New POS Machine'; ?>
            </div>

            <form method="post" class="row g-3">
                <input type="hidden" name="id" value="<?php echo (int)$form['id']; ?>">

                <div class="col-12">
                    <label class="form-label">Linked Bank Account</label>
                    <select name="bank_detail_id" class="form-select" required>
                        <option value="">Select bank account</option>
                        <?php foreach ($bankAccounts as $bank): ?>
                            <option value="<?php echo (int)$bank['ID']; ?>" <?php echo (string)$form['bank_detail_id'] === (string)$bank['ID'] ? 'selected' : ''; ?>>
                                <?php echo h(bank_label($bank)); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <div class="bank-select-note">Only active bank accounts from tblbankdetails are shown.</div>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Machine Name</label>
                    <input type="text" name="machine_name" class="form-control" value="<?php echo h($form['machine_name']); ?>" maxlength="120" placeholder="Front Office POS" required>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Status</label>
                    <select name="status" class="form-select">
                        <option value="1" <?php echo $form['status'] === '1' ? 'selected' : ''; ?>>Active</option>
                        <option value="0" <?php echo $form['status'] === '0' ? 'selected' : ''; ?>>Inactive</option>
                    </select>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Terminal ID</label>
                    <input type="text" name="terminal_id" class="form-control" value="<?php echo h($form['terminal_id']); ?>" maxlength="80" required>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Merchant ID</label>
                    <input type="text" name="merchant_id" class="form-control" value="<?php echo h($form['merchant_id']); ?>" maxlength="80">
                </div>

                <div class="col-md-6">
                    <label class="form-label">Serial No</label>
                    <input type="text" name="serial_no" class="form-control" value="<?php echo h($form['serial_no']); ?>" maxlength="100">
                </div>

                <div class="col-md-6">
                    <label class="form-label">Provider</label>
                    <input type="text" name="provider" class="form-control" value="<?php echo h($form['provider']); ?>" maxlength="100" placeholder="Bank / Paynow / Swipe provider">
                </div>

                <div class="col-md-6">
                    <label class="form-label">Location</label>
                    <input type="text" name="location" class="form-control" value="<?php echo h($form['location']); ?>" maxlength="150" placeholder="Reception / Restaurant / Bar">
                </div>

                <div class="col-md-3">
                    <label class="form-label">Settlement Days</label>
                    <input type="number" min="0" name="settlement_days" class="form-control" value="<?php echo h($form['settlement_days']); ?>">
                </div>

                <div class="col-md-3">
                    <label class="form-label">Commission %</label>
                    <input type="number" min="0" step="0.01" name="commission_percent" class="form-control" value="<?php echo h($form['commission_percent']); ?>">
                </div>

                <div class="col-12">
                    <label class="form-label">Notes</label>
                    <textarea name="notes" class="form-control" rows="3" maxlength="1000"><?php echo h($form['notes']); ?></textarea>
                </div>

                <div class="col-12 d-flex gap-2">
                    <button type="submit" name="save_pos_machine" value="1" class="btn btn-primary">
                        <i class="bi bi-save me-2"></i><?php echo $editing ? 'Update POS Machine' : 'Save POS Machine'; ?>
                    </button>
                    <a href="pos_machines.php" class="btn btn-light">Reset</a>
                </div>
            </form>
        </div>
    </div>

    <div class="col-xl-7">
        <div class="card panel-card">
            <div class="card-header bg-white">
                <div class="d-flex flex-wrap justify-content-between align-items-center gap-2">
                    <h5 class="mb-0">Registered POS Machines</h5>
                    <form method="get" class="d-flex flex-wrap gap-2">
                        <input type="text" name="q" class="form-control" placeholder="Search POS machines..." value="<?php echo h($search); ?>" style="min-width:220px;">
                        <select name="status" class="form-select" style="width:150px;">
                            <option value="" <?php echo $statusFilter === '' ? 'selected' : ''; ?>>All</option>
                            <option value="1" <?php echo $statusFilter === '1' ? 'selected' : ''; ?>>Active</option>
                            <option value="0" <?php echo $statusFilter === '0' ? 'selected' : ''; ?>>Inactive</option>
                        </select>
                        <button class="btn btn-outline-secondary">Search</button>
                    </form>
                </div>
            </div>

            <div class="card-body p-0">
                <div class="table-responsive pos-table-wrap">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>POS Machine</th>
                                <th>Terminal</th>
                                <th>Linked Bank</th>
                                <th>Settlement</th>
                                <th>Status</th>
                                <th class="text-end">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!$machines): ?>
                                <tr>
                                    <td colspan="7" class="text-center text-muted py-4">No POS machines found.</td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($machines as $row): ?>
                                    <tr>
                                        <td><?php echo (int)$row['id']; ?></td>
                                        <td>
                                            <div class="fw-semibold"><?php echo h($row['machine_name']); ?></div>
                                            <div class="small-muted"><?php echo h($row['location'] ?? ''); ?></div>
                                            <?php if (!empty($row['provider'])): ?>
                                                <div class="small-muted">Provider: <?php echo h($row['provider']); ?></div>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <div><?php echo h($row['terminal_id']); ?></div>
                                            <?php if (!empty($row['merchant_id'])): ?>
                                                <div class="small-muted">Merchant: <?php echo h($row['merchant_id']); ?></div>
                                            <?php endif; ?>
                                            <?php if (!empty($row['serial_no'])): ?>
                                                <div class="small-muted">Serial: <?php echo h($row['serial_no']); ?></div>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <div class="fw-semibold"><?php echo h($row['Bank']); ?></div>
                                            <div class="small-muted"><?php echo h($row['AccountName']); ?></div>
                                            <div class="small-muted">
                                                <?php echo h($row['AccountNo']); ?>
                                                <?php if (!empty($row['CurrencyCode'])): ?> | <?php echo h($row['CurrencyCode']); ?><?php endif; ?>
                                            </div>
                                            <?php if (!empty($row['property_name'])): ?>
                                                <div class="small-muted"><?php echo h($row['property_name']); ?></div>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <div><?php echo (int)$row['settlement_days']; ?> day(s)</div>
                                            <div class="small-muted"><?php echo number_format((float)$row['commission_percent'], 2); ?>% commission</div>
                                        </td>
                                        <td>
                                            <?php if ((int)$row['status'] === 1): ?>
                                                <span class="badge text-bg-success">Active</span>
                                            <?php else: ?>
                                                <span class="badge text-bg-secondary">Inactive</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-end">
                                            <div class="d-inline-flex gap-2">
                                                <a href="pos_machines.php?edit=<?php echo (int)$row['id']; ?>" class="btn btn-sm btn-primary">Edit</a>
                                                <a href="pos_machines.php?delete=<?php echo (int)$row['id']; ?>"
                                                   class="btn btn-sm btn-outline-danger"
                                                   onclick="return confirm('Delete this POS machine?');">
                                                    Delete
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

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