<?php
require_once 'config/db.php';

// --- ALL redirect-based actions BEFORE header.php ---

if (isset($_GET['delete'])) {
    try {
        $pdo->prepare("DELETE FROM sales_agents WHERE id=?")->execute([(int)$_GET['delete']]);
        header("Location: sales_agents.php?msg=deleted"); exit;
    } catch(PDOException $e) { $del_error = "Cannot delete: agent may have assigned leads."; }
}

if (isset($_GET['toggle'])) {
    $ag = $pdo->prepare("SELECT is_active FROM sales_agents WHERE id=?");
    $ag->execute([(int)$_GET['toggle']]); $ag = $ag->fetch();
    if ($ag) {
        $pdo->prepare("UPDATE sales_agents SET is_active=? WHERE id=?")->execute([!$ag['is_active'], (int)$_GET['toggle']]);
        header("Location: sales_agents.php?msg=toggled"); exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_agent'])) {
    $name   = trim($_POST['name']);
    $phone  = trim($_POST['phone']        ?? '');
    $email  = trim($_POST['email']        ?? '');
    $desig  = trim($_POST['designation']  ?? 'Sales Agent');
    $uname  = trim($_POST['username']     ?? '');
    $pass   = $_POST['password']          ?? '';
    $active = isset($_POST['is_active'])  ? 1 : 0;
    $id     = !empty($_POST['id'])        ? (int)$_POST['id'] : null;
    if (!empty($name)) {
        $username_taken = false;
        if (!empty($uname)) {
            // Check username uniqueness
            $chk = $pdo->prepare("SELECT id FROM sales_agents WHERE username=? AND id!=?");
            $chk->execute([$uname, $id ?? 0]);
            if ($chk->fetch()) { 
                $save_error = "Username '$uname' is already taken."; 
                $username_taken = true;
            }
        }
        
        if (!$username_taken) {
            try {
                if ($id) {
                    if (!empty($pass)) {
                        $pdo->prepare("UPDATE sales_agents SET name=?,phone=?,email=?,designation=?,username=?,password_hash=?,is_active=? WHERE id=?")
                            ->execute([$name,$phone,$email,$desig,$uname?:null,password_hash($pass, PASSWORD_DEFAULT),$active,$id]);
                    } else {
                        $pdo->prepare("UPDATE sales_agents SET name=?,phone=?,email=?,designation=?,username=?,is_active=? WHERE id=?")
                            ->execute([$name,$phone,$email,$desig,$uname?:null,$active,$id]);
                    }
                } else {
                    $hash = !empty($pass) ? password_hash($pass, PASSWORD_DEFAULT) : null;
                    $pdo->prepare("INSERT INTO sales_agents (name,phone,email,designation,username,password_hash,is_active) VALUES (?,?,?,?,?,?,?)")
                        ->execute([$name,$phone,$email,$desig,$uname?:null,$hash,$active]);
                }
                header("Location: sales_agents.php?msg=saved"); exit;
            } catch(PDOException $e) { $save_error = "Error: " . $e->getMessage(); }
        }
    } else {
        $save_error = "Agent name is required.";
    }
}

require_once 'includes/header.php';

// Flash messages
$msgs = ['deleted'=>'Agent deleted.', 'saved'=>'Agent saved successfully.', 'toggled'=>'Agent status updated.'];
if (isset($_GET['msg']))  $success = $msgs[$_GET['msg']] ?? '';
if (isset($del_error))   $error   = $del_error;
if (isset($save_error))  $error   = $save_error;

// Form defaults (for Add / Edit)
$edit_id = null;
$f = ['name'=>'','phone'=>'','email'=>'','designation'=>'Sales Agent','is_active'=>1];

if (isset($_GET['edit'])) {
    $edit_id = (int)$_GET['edit'];
    $row = $pdo->prepare("SELECT * FROM sales_agents WHERE id=?");
    $row->execute([$edit_id]); $row = $row->fetch();
    if ($row) $f = $row;
}

// Fetch agents list with lead count
$agents = $pdo->query("
    SELECT a.*, COUNT(l.id) as lead_count
    FROM sales_agents a
    LEFT JOIN leads l ON l.assigned_agent_id = a.id AND l.is_junk = 0
    GROUP BY a.id ORDER BY a.name
")->fetchAll() ?: [];
?>


<div class="dashboard-content">
    <!-- Header -->
    <div class="welcome-banner" style="margin-bottom:20px; padding:20px; display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:12px;">
        <div>
            <h2><i class="fa-solid fa-user-tie"></i> Sales Agents</h2>
            <p>Create agents and assign leads for follow-up tracking.</p>
        </div>
        <a href="sales_agents.php" style="background:#fff; color:var(--primary); padding:10px 18px; border-radius:8px; font-weight:600; text-decoration:none; display:inline-flex; align-items:center; gap:7px;">
            <i class="fa-solid fa-plus"></i> Add New Agent
        </a>
    </div>

    <?php if(isset($success)): ?>
        <div class="badge badge-completed" style="display:block; padding:14px; margin-bottom:16px; font-size:0.95rem;"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>
    <?php if(isset($error)): ?>
        <div style="display:block; padding:14px; margin-bottom:16px; background:#fee2e2; color:#ef4444; border-radius:8px; font-weight:600;"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <div style="display:grid; grid-template-columns:340px 1fr; gap:24px; align-items:start;">

        <!-- Add / Edit Form -->
        <div class="data-card" style="background:#fff; padding:24px; border-radius:14px;">
            <h3 style="margin:0 0 20px; color:var(--dark); display:flex; align-items:center; gap:8px;">
                <i class="fa-solid <?= $edit_id ? 'fa-pen' : 'fa-user-plus' ?>" style="color:var(--primary);"></i>
                <?= $edit_id ? 'Edit Agent' : 'New Agent' ?>
            </h3>
            <form action="sales_agents.php" method="POST">
                <input type="hidden" name="id" value="<?= htmlspecialchars((string)$edit_id) ?>">

                <div style="margin-bottom:16px;">
                    <label style="display:block; margin-bottom:7px; font-weight:700; font-size:0.82rem; color:#64748b;">Full Name *</label>
                    <input type="text" name="name" value="<?= htmlspecialchars($f['name']) ?>" required placeholder="Agent's full name" style="width:100%; padding:11px 14px; font-family:inherit;">
                </div>
                <div style="margin-bottom:16px;">
                    <label style="display:block; margin-bottom:7px; font-weight:700; font-size:0.82rem; color:#64748b;">Phone</label>
                    <input type="text" name="phone" value="<?= htmlspecialchars($f['phone'] ?? '') ?>" placeholder="+91 9XXXXXXXXX" style="width:100%; padding:11px 14px; font-family:inherit;">
                </div>
                <div style="margin-bottom:16px;">
                    <label style="display:block; margin-bottom:7px; font-weight:700; font-size:0.82rem; color:#64748b;">Email</label>
                    <input type="email" name="email" value="<?= htmlspecialchars($f['email'] ?? '') ?>" placeholder="agent@email.com" style="width:100%; padding:11px 14px; font-family:inherit;">
                </div>
                <div style="margin-bottom:16px;">
                    <label style="display:block; margin-bottom:7px; font-weight:700; font-size:0.82rem; color:#64748b;">Designation</label>
                    <input type="text" name="designation" value="<?= htmlspecialchars($f['designation'] ?? 'Sales Agent') ?>" placeholder="e.g. Senior Sales Agent" style="width:100%; padding:11px 14px; font-family:inherit;">
                </div>

                <!-- Login Credentials -->
                <div style="background:#f8fafc; border:2px solid #e2e8f0; border-radius:10px; padding:16px; margin-bottom:16px;">
                    <div style="font-size:0.72rem; font-weight:800; color:#94a3b8; text-transform:uppercase; letter-spacing:0.06em; margin-bottom:12px;">
                        <i class="fa-solid fa-key" style="margin-right:5px; color:var(--primary);"></i>Portal Login Credentials
                    </div>
                    <div style="margin-bottom:12px;">
                        <label style="display:block; margin-bottom:6px; font-weight:700; font-size:0.82rem; color:#64748b;">Username</label>
                        <input type="text" name="username" value="<?= htmlspecialchars($f['username'] ?? '') ?>" placeholder="e.g. john.doe" style="width:100%; padding:10px 14px; font-family:inherit;" autocomplete="new-password">
                    </div>
                    <div>
                        <label style="display:block; margin-bottom:6px; font-weight:700; font-size:0.82rem; color:#64748b;">
                            Password <?= $edit_id ? '<span style="font-weight:400;color:#94a3b8;">(leave blank to keep current)</span>' : '' ?>
                        </label>
                        <div style="position:relative;">
                            <input type="password" name="password" id="agPwd" placeholder="<?= $edit_id ? '••••••••' : 'Set a password' ?>" style="width:100%; padding:10px 44px 10px 14px; font-family:inherit;" autocomplete="new-password">
                            <button type="button" onclick="toggleAgPwd()" style="position:absolute;right:10px;top:50%;transform:translateY(-50%);background:none;border:none;cursor:pointer;color:#94a3b8;font-size:0.9rem;"><i class="fa-solid fa-eye" id="agEye"></i></button>
                        </div>
                    </div>
                    <div style="margin-top:10px; font-size:0.78rem; color:#94a3b8;">
                        Agent portal login: <a href="agent/login.php" target="_blank" style="color:var(--primary); font-weight:700;">admin/agent/login.php</a>
                    </div>
                </div>
                <div style="margin-bottom:22px; display:flex; align-items:center; gap:10px;">
                    <input type="checkbox" name="is_active" id="is_active" style="width:18px; height:18px; accent-color:var(--primary); cursor:pointer;" <?= !empty($f['is_active']) ? 'checked' : '' ?>>
                    <label for="is_active" style="font-weight:600; font-size:0.9rem; cursor:pointer;">Active Agent</label>
                </div>
                <div style="display:flex; gap:10px;">
                    <button type="submit" name="save_agent" style="flex:1; padding:12px; background:var(--primary); color:#fff; border:none; border-radius:8px; font-weight:700; cursor:pointer; font-size:0.95rem;">
                        <i class="fa-solid fa-check" style="margin-right:6px;"></i><?= $edit_id ? 'Update Agent' : 'Create Agent' ?>
                    </button>
                    <?php if($edit_id): ?>
                        <a href="sales_agents.php" style="padding:12px 18px; background:#f1f5f9; color:#64748b; border-radius:8px; font-weight:600; text-decoration:none; display:inline-flex; align-items:center;">Cancel</a>
                    <?php endif; ?>
                </div>
            </form>
        </div>

        <!-- Agents List -->
        <div class="recent-activity" style="margin:0; padding:0;">
            <div class="table-responsive">
                <table class="admin-table">
                    <thead>
                        <tr>
                            <th style="padding-left:20px; width:60px;">#</th>
                            <th>Agent</th>
                            <th>Contact</th>
                            <th style="text-align:center;">Assigned Leads</th>
                            <th style="text-align:center;">Status</th>
                            <th style="text-align:right; padding-right:20px;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (count($agents) > 0): $sno=1; ?>
                            <?php foreach ($agents as $ag): ?>
                            <tr>
                                <td style="padding-left:20px; color:#94a3b8; font-size:0.85rem;">#<?= $sno++ ?></td>
                                <td>
                                    <div style="font-weight:700; color:var(--dark);"><?= htmlspecialchars($ag['name']) ?></div>
                                    <div style="font-size:0.8rem; color:#94a3b8;"><?= htmlspecialchars($ag['designation'] ?? 'Sales Agent') ?></div>
                                </td>
                                <td>
                                    <?php if(!empty($ag['phone'])): ?>
                                        <div style="font-size:0.88rem;"><i class="fa-solid fa-phone" style="color:#94a3b8; margin-right:5px; width:14px;"></i><?= htmlspecialchars($ag['phone']) ?></div>
                                    <?php endif; ?>
                                    <?php if(!empty($ag['email'])): ?>
                                        <div style="font-size:0.82rem; color:#64748b;"><i class="fa-solid fa-envelope" style="color:#94a3b8; margin-right:5px; width:14px;"></i><?= htmlspecialchars($ag['email']) ?></div>
                                    <?php endif; ?>
                                </td>
                                <td style="text-align:center;">
                                    <a href="leads.php?agent_id=<?= $ag['id'] ?>" style="display:inline-flex; align-items:center; gap:5px; background:#e0f2fe; color:#0369a1; padding:5px 12px; border-radius:14px; font-weight:700; font-size:0.88rem; text-decoration:none;">
                                        <i class="fa-solid fa-users" style="font-size:0.75rem;"></i> <?= $ag['lead_count'] ?>
                                    </a>
                                </td>
                                <td style="text-align:center;">
                                    <a href="sales_agents.php?toggle=<?= $ag['id'] ?>" style="display:inline-flex; align-items:center; gap:5px; padding:5px 12px; border-radius:14px; font-size:0.82rem; font-weight:700; text-decoration:none;
                                        background:<?= $ag['is_active'] ? '#dcfce7' : '#fee2e2' ?>;
                                        color:<?= $ag['is_active'] ? '#16a34a' : '#ef4444' ?>;">
                                        <i class="fa-solid fa-circle" style="font-size:0.5rem;"></i>
                                        <?= $ag['is_active'] ? 'Active' : 'Inactive' ?>
                                    </a>
                                </td>
                                <td style="text-align:right; padding-right:20px;">
                                    <a href="sales_agents.php?edit=<?= $ag['id'] ?>" style="display:inline-flex; align-items:center; justify-content:center; width:34px; height:34px; background:#e0f2fe; color:var(--primary); border-radius:8px; margin-right:5px; text-decoration:none;"><i class="fa-solid fa-pen"></i></a>
                                    <a href="sales_agents.php?delete=<?= $ag['id'] ?>" onclick="return confirm('Delete this agent? Their leads will be unassigned.')" style="display:inline-flex; align-items:center; justify-content:center; width:34px; height:34px; background:#fee2e2; color:#ef4444; border-radius:8px; text-decoration:none;"><i class="fa-solid fa-trash"></i></a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="6" style="text-align:center; padding:50px; color:#94a3b8;">
                                    <i class="fa-solid fa-user-tie" style="font-size:2.5rem; color:#e2e8f0; display:block; margin-bottom:12px;"></i>
                                    No agents yet. Create your first sales agent!
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<style>
@media (max-width:900px) {
    .dashboard-content > div:last-child { grid-template-columns: 1fr !important; }
}

@media (max-width: 768px) {
    /* Force compact ROW view — override the global card transform */
    .admin-table, .admin-table thead, .admin-table tbody,
    .admin-table th, .admin-table td, .admin-table tr {
        display: revert !important;
    }
    .admin-table { width:100%; border-collapse:collapse; }
    .admin-table thead tr { position: relative !important; top: auto !important; left: auto !important; }
    .admin-table th, .admin-table td {
        padding: 10px 5px !important;
        font-size: 0.78rem !important;
        vertical-align: middle !important;
        min-height: auto !important;
        padding-left: 5px !important;
        border-bottom: 1px solid #f1f5f9 !important;
        border: none !important;
        border-bottom: 1px solid #f1f5f9 !important;
    }
    .admin-table tr {
        border: none !important;
        border-radius: 0 !important;
        margin-bottom: 0 !important;
        padding: 0 !important;
        box-shadow: none !important;
        display: table-row !important;
    }
    .admin-table td:before { display: none !important; content: none !important; }
    
    /* Hide non-essential columns on mobile */
    .admin-table th:nth-child(1), .admin-table td:nth-child(1), /* # */
    .admin-table th:nth-child(3), .admin-table td:nth-child(3)  /* Contact */
    { display: none !important; }

    .dashboard-content { padding: 10px !important; }
}
</style>

<script>
function toggleAgPwd(){
    const p=document.getElementById('agPwd'),e=document.getElementById('agEye');
    p.type=p.type==='password'?'text':'password';
    e.className=p.type==='password'?'fa-solid fa-eye':'fa-solid fa-eye-slash';
}
</script>

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

