<?php
/**
 * Edit Agent
 * LandSales Pro - Edit existing agent
 */
define('APP_RUNNING', true);
require_once '../../db_connect.php';
require_once '../../includes/auth.php';
require_once '../../includes/subscription.php';
require_once '../../includes/functions.php';

initSecureSession();
requireAuth();
requireSubscription();
requireManagePermission('agents');

$userId = $_SESSION['user_id'];
$agentId = intval($_GET['id'] ?? 0);

// Get agent
$agent = db_fetch_one("SELECT * FROM agents WHERE id = ? AND user_id = ?", 'ii', [$agentId, $userId]);
if (!$agent) {
    setFlashMessage('Agent not found', 'error');
    header('Location: index.php');
    exit;
}

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $fullName = trim($_POST['full_name'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $commissionRate = floatval($_POST['commission_rate'] ?? 5.00);
    $status = $_POST['status'] ?? 'active';

    // Validation
    if (empty($fullName)) $errors[] = "Full name is required";
    if (empty($phone)) $errors[] = "Phone number is required";
    if ($email && !filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Invalid email format";
    if ($commissionRate < 0 || $commissionRate > 100) $errors[] = "Commission rate must be between 0 and 100";

    // Check for duplicate phone (excluding current)
    if (empty($errors)) {
        $existing = db_fetch_one("SELECT id FROM agents WHERE user_id = ? AND phone = ? AND id != ?", 'isi', [$userId, $phone, $agentId]);
        if ($existing) {
            $errors[] = "An agent with this phone number already exists";
        }
    }

    if (empty($errors)) {
        $sql = "UPDATE agents SET full_name = ?, phone = ?, email = ?, commission_rate = ?, status = ? WHERE id = ? AND user_id = ?";

        if (db_execute($sql, 'sssdsii', [$fullName, $phone, $email ?: null, $commissionRate, $status, $agentId, $userId])) {
            logActivity('agent_updated', "Updated agent: {$fullName}");
            setFlashMessage("Agent '{$fullName}' updated successfully!", 'success');
            header('Location: view.php?id=' . $agentId);
            exit;
        } else {
            $errors[] = "Failed to update agent. Please try again.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Agent - <?php echo APP_NAME; ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/font-awesome/css/all.min.css">
</head>
<body>
    <?php include '../includes/sidebar.php'; ?>

    <div class="main-content">
        <div class="top-header">
            <button class="menu-toggle" onclick="toggleSidebar()">
                <i class="fas fa-bars"></i>
            </button>
            <h1 class="page-title">Edit Agent</h1>
            <div class="header-actions">
                <a href="view.php?id=<?php echo $agentId; ?>" class="btn btn-outline">
                    <i class="fas fa-arrow-left"></i> Back
                </a>
            </div>
        </div>

        <div class="content-wrapper">
            <div class="form-container">
                <?php if (!empty($errors)): ?>
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle"></i>
                    <ul>
                        <?php foreach ($errors as $error): ?>
                        <li><?php echo htmlspecialchars($error); ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
                <?php endif; ?>

                <form method="POST" class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-user-edit"></i> Agent Information</h3>
                    </div>
                    <div class="card-body">
                        <div class="form-group">
                            <label for="full_name">Full Name *</label>
                            <input type="text" name="full_name" id="full_name" class="form-control"
                                   value="<?php echo htmlspecialchars($_POST['full_name'] ?? $agent['full_name']); ?>"
                                   placeholder="e.g., John Mwamba" required>
                        </div>

                        <div class="form-row">
                            <div class="form-group">
                                <label for="phone">Phone Number *</label>
                                <input type="tel" name="phone" id="phone" class="form-control"
                                       value="<?php echo htmlspecialchars($_POST['phone'] ?? $agent['phone']); ?>"
                                       placeholder="e.g., 0712345678" required>
                            </div>
                            <div class="form-group">
                                <label for="email">Email</label>
                                <input type="email" name="email" id="email" class="form-control"
                                       value="<?php echo htmlspecialchars($_POST['email'] ?? $agent['email'] ?? ''); ?>"
                                       placeholder="e.g., john@example.com">
                            </div>
                        </div>

                        <div class="form-row">
                            <div class="form-group">
                                <label for="commission_rate">Commission Rate (%)</label>
                                <input type="number" name="commission_rate" id="commission_rate" class="form-control"
                                       value="<?php echo htmlspecialchars($_POST['commission_rate'] ?? $agent['commission_rate']); ?>"
                                       min="0" max="100" step="0.1" placeholder="e.g., 5.00">
                                <small class="form-text">Percentage of sale price the agent earns</small>
                            </div>
                            <div class="form-group">
                                <label for="status">Status</label>
                                <select name="status" id="status" class="form-control">
                                    <option value="active" <?php echo ($_POST['status'] ?? $agent['status']) === 'active' ? 'selected' : ''; ?>>Active</option>
                                    <option value="inactive" <?php echo ($_POST['status'] ?? $agent['status']) === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="card-footer">
                        <a href="view.php?id=<?php echo $agentId; ?>" class="btn btn-outline">Cancel</a>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-check"></i> Update Agent
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <style>
        body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; margin: 0; background: #f1f5f9; }
        .header-actions { display: flex; gap: 0.75rem; }
        .btn { padding: 0.625rem 1.25rem; border-radius: 8px; font-weight: 500; text-decoration: none; display: inline-flex; align-items: center; gap: 0.5rem; transition: all 0.2s; border: none; cursor: pointer; font-size: 0.875rem; }
        .btn-primary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .btn-outline { border: 1px solid #e2e8f0; background: white; color: #64748b; }

        .form-container { max-width: 600px; }

        .alert { padding: 1rem 1.5rem; border-radius: 10px; margin-bottom: 1.5rem; display: flex; gap: 0.75rem; }
        .alert-danger { background: #fef2f2; border: 1px solid #fecaca; color: #991b1b; }
        .alert ul { margin: 0; padding-left: 1rem; }

        .card { background: white; border-radius: 14px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); overflow: hidden; }
        .card-header { padding: 1.25rem 1.5rem; border-bottom: 1px solid #f1f5f9; background: #f8fafc; }
        .card-header h3 { margin: 0; font-size: 1rem; font-weight: 600; color: #1e293b; display: flex; align-items: center; gap: 0.5rem; }
        .card-header h3 i { color: #667eea; }
        .card-body { padding: 1.5rem; }
        .card-footer { padding: 1rem 1.5rem; border-top: 1px solid #f1f5f9; display: flex; justify-content: flex-end; gap: 1rem; }

        .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
        .form-group { margin-bottom: 1.25rem; }
        .form-group:last-child { margin-bottom: 0; }
        .form-group label { display: block; margin-bottom: 0.5rem; font-weight: 500; color: #374151; font-size: 0.875rem; }
        .form-control { width: 100%; padding: 0.75rem 1rem; border: 1px solid #e2e8f0; border-radius: 8px; font-size: 0.9rem; transition: all 0.2s; box-sizing: border-box; }
        .form-control:focus { outline: none; border-color: #667eea; box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1); }
        .form-text { font-size: 0.75rem; color: #64748b; margin-top: 0.25rem; }

        @media (max-width: 576px) {
            .form-row { grid-template-columns: 1fr; }
            .card-footer { flex-direction: column-reverse; }
            .card-footer .btn { width: 100%; justify-content: center; }
        }
    </style>
</body>
</html>
