<?php
require_once __DIR__ . '/../includes/auth.php';
requireLogin();
requirePermission('companies.manage');

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

function esc($v){ return htmlspecialchars((string)($v ?? ''), ENT_QUOTES, 'UTF-8'); }

/*
|--------------------------------------------------------------------------
| ACTIONS (POST) - Activate / Suspend / Archive
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'], $_POST['company_id'])) {

    $companyId = (int)$_POST['company_id'];
    $action = $_POST['action'];

    $allowed = ['activate','suspend','archive'];
    if (!in_array($action, $allowed, true)) {
        die("Invalid action.");
    }

    $newStatus = 'ACTIVE';
    if ($action === 'suspend') $newStatus = 'SUSPENDED';
    if ($action === 'archive') $newStatus = 'ARCHIVED';

    $upd = $pdo->prepare("UPDATE companies SET status=? WHERE id=?");
    $upd->execute([$newStatus, $companyId]);

    header("Location: companies.php");
    exit;
}

/*
|--------------------------------------------------------------------------
| FILTERS
|--------------------------------------------------------------------------
*/
$q = trim($_GET['q'] ?? '');
$type = trim($_GET['type'] ?? '');
$status = trim($_GET['status'] ?? '');

$page = max((int)($_GET['page'] ?? 1), 1);
$limit = 15;
$offset = ($page - 1) * $limit;

$where = "WHERE 1=1";
$params = [];

if ($q !== '') {
    $where .= " AND (company_name LIKE ? OR email LIKE ? OR phone LIKE ? OR city LIKE ? OR province LIKE ?)";
    $params[] = "%$q%";
    $params[] = "%$q%";
    $params[] = "%$q%";
    $params[] = "%$q%";
    $params[] = "%$q%";
}

if ($type !== '') {
    $where .= " AND company_type = ?";
    $params[] = $type;
}

if ($status !== '') {
    $where .= " AND status = ?";
    $params[] = $status;
}

/*
|--------------------------------------------------------------------------
| COUNT
|--------------------------------------------------------------------------
*/
$countStmt = $pdo->prepare("SELECT COUNT(*) FROM companies $where");
$countStmt->execute($params);
$total = (int)$countStmt->fetchColumn();
$totalPages = max((int)ceil($total / $limit), 1);

/*
|--------------------------------------------------------------------------
| DATA
|--------------------------------------------------------------------------
*/
$sql = "SELECT * FROM companies $where ORDER BY created_at DESC LIMIT $limit OFFSET $offset";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$companies = $stmt->fetchAll(PDO::FETCH_ASSOC);

/*
|--------------------------------------------------------------------------
| LAYOUT
|--------------------------------------------------------------------------
*/
require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/sidebar.php';
?>

<div class="main-content">

    <div class="page-header">
        <h2>Companies</h2>
        <p class="page-subtitle">Enterprise directory for Installers, Distributors and Clients.</p>
    </div>

    <div class="breadcrumbs" style="font-size:13px;color:#6b7280;margin-bottom:14px;">
        Dashboard › <span style="color:var(--edm-orange);font-weight:600;">Companies</span>
    </div>

    <div class="table-wrap" style="padding:16px;margin-bottom:16px;">
        <form method="GET" style="display:flex;gap:12px;flex-wrap:wrap;align-items:end;">
            <div style="flex:1;min-width:220px;">
                <label style="font-size:12px;color:#6b7280;">Search</label>
                <input type="text" name="q" value="<?= esc($q) ?>" placeholder="Name, email, phone, city..."
                       style="width:100%;padding:10px;border:1px solid #e5e7eb;border-radius:10px;">
            </div>

            <div style="min-width:180px;">
                <label style="font-size:12px;color:#6b7280;">Type</label>
                <select name="type" style="width:100%;padding:10px;border:1px solid #e5e7eb;border-radius:10px;">
                    <option value="">All</option>
                    <option value="INSTALLER" <?= $type==='INSTALLER'?'selected':'' ?>>Installer</option>
                    <option value="DISTRIBUTOR" <?= $type==='DISTRIBUTOR'?'selected':'' ?>>Distributor</option>
                    <option value="CLIENT" <?= $type==='CLIENT'?'selected':'' ?>>Client</option>
                </select>
            </div>

            <div style="min-width:180px;">
                <label style="font-size:12px;color:#6b7280;">Status</label>
                <select name="status" style="width:100%;padding:10px;border:1px solid #e5e7eb;border-radius:10px;">
                    <option value="">All</option>
                    <option value="ACTIVE" <?= $status==='ACTIVE'?'selected':'' ?>>Active</option>
                    <option value="SUSPENDED" <?= $status==='SUSPENDED'?'selected':'' ?>>Suspended</option>
                    <option value="LEAD" <?= $status==='LEAD'?'selected':'' ?>>Lead</option>
                    <option value="ARCHIVED" <?= $status==='ARCHIVED'?'selected':'' ?>>Archived</option>
                </select>
            </div>

            <button type="submit" class="action-btn" style="padding:10px 14px;border-radius:10px;border:none;background:var(--edm-orange);color:#fff;font-weight:700;cursor:pointer;">
                Apply
            </button>

            <a href="companies.php" class="action-btn gray" style="padding:10px 14px;border-radius:10px;text-decoration:none;border:1px solid #e5e7eb;">
                Reset
            </a>

            <a href="add_company.php" class="action-btn black" style="padding:10px 14px;border-radius:10px;text-decoration:none;background:#111827;color:#fff;">
                + Add Company
            </a>
        </form>
    </div>

    <div class="table-wrap">
        <div style="padding:14px 16px;border-bottom:1px solid #e5e7eb;color:#6b7280;font-size:13px;">
            Showing <strong><?= count($companies) ?></strong> of <strong><?= $total ?></strong>
        </div>

        <div style="overflow-x:auto;-webkit-overflow-scrolling:touch;">
            <table>
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Type</th>
                        <th>Contact</th>
                        <th>Province</th>
                        <th>City</th>
                        <th>Status</th>
                        <th>Created</th>
                        <th style="width:260px;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (!$companies): ?>
                    <tr><td colspan="8" style="padding:16px;color:#6b7280;">No companies found.</td></tr>
                <?php else: ?>
                    <?php foreach ($companies as $c): ?>
                        <?php
                            $st = strtoupper((string)($c['status'] ?? 'ACTIVE'));
                            $pillClass = 'IN_STOCK';
                            if ($st === 'ACTIVE') $pillClass = 'INSTALLED';
                            if ($st === 'SUSPENDED') $pillClass = 'FAULTY';
                            if ($st === 'LEAD') $pillClass = 'WITH_DISTRIBUTOR';
                            if ($st === 'ARCHIVED') $pillClass = 'IN_STOCK';
                        ?>
                        <tr>
                            <td><?= esc($c['company_name']) ?></td>
                            <td><strong><?= esc($c['company_type']) ?></strong></td>
                            <td>
                                <div><?= esc($c['contact_person']) ?></div>
                                <div style="font-size:12px;color:#6b7280;"><?= esc($c['email']) ?> • <?= esc($c['phone']) ?></div>
                            </td>
                            <td><?= esc($c['province']) ?></td>
                            <td><?= esc($c['city']) ?></td>
                            <td><span class="status <?= esc($pillClass) ?>"><?= esc($st) ?></span></td>
                            <td><?= esc($c['created_at']) ?></td>
                            <td>
                                <a class="action-btn" href="view_company.php?id=<?= (int)$c['id'] ?>" style="text-decoration:none;">View</a>
                                <a class="action-btn black" href="edit_company.php?id=<?= (int)$c['id'] ?>" style="text-decoration:none;">Edit</a>

                                <?php if ($st !== 'ACTIVE'): ?>
                                    <form method="POST" style="display:inline;">
                                        <input type="hidden" name="company_id" value="<?= (int)$c['id'] ?>">
                                        <input type="hidden" name="action" value="activate">
                                        <button class="action-btn" type="submit">Activate</button>
                                    </form>
                                <?php else: ?>
                                    <form method="POST" style="display:inline;">
                                        <input type="hidden" name="company_id" value="<?= (int)$c['id'] ?>">
                                        <input type="hidden" name="action" value="suspend">
                                        <button class="action-btn gray" type="submit">Suspend</button>
                                    </form>
                                <?php endif; ?>

                                <form method="POST" style="display:inline;" onsubmit="return confirm('Archive this company?');">
                                    <input type="hidden" name="company_id" value="<?= (int)$c['id'] ?>">
                                    <input type="hidden" name="action" value="archive">
                                    <button class="action-btn gray" type="submit">Archive</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>

        <div style="padding:14px 16px;border-top:1px solid #e5e7eb;display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap;">
            <div style="font-size:13px;color:#6b7280;">Page <strong><?= $page ?></strong> of <strong><?= $totalPages ?></strong></div>

            <div style="display:flex;gap:8px;align-items:center;">
                <?php
                    $qs = $_GET;
                    if ($page > 1) {
                        $qs['page'] = $page - 1;
                        echo '<a class="action-btn" style="text-decoration:none;" href="?' . http_build_query($qs) . '">Previous</a>';
                    }
                    if ($page < $totalPages) {
                        $qs['page'] = $page + 1;
                        echo '<a class="action-btn" style="text-decoration:none;" href="?' . http_build_query($qs) . '">Next</a>';
                    }
                ?>
            </div>
        </div>
    </div>

</div>

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