<?php
include "dbconnect.php";

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

$agent = null;
$error = '';

// Get ID either from GET or POST (prefer POST on submit)
$id = 0;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
} elseif (isset($_GET['id']) && is_numeric($_GET['id'])) {
    $id = (int)$_GET['id'];
}

if ($id <= 0) {
    echo "<div class='alert alert-danger text-center mt-5'>Invalid or missing agent ID!</div>";
    exit;
}

// On POST, update agent data
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = trim($_POST['name']);
    $father_name = trim($_POST['father_name']);
    $qualification = trim($_POST['qualification']);
    $mobile_no = trim($_POST['mobile_no']);
    $email_id = trim($_POST['email_id']);
    $address = trim($_POST['address']);
    $city = trim($_POST['city']);
    $state = trim($_POST['state']);
    $message = trim($_POST['message']);
    $adharno = trim($_POST['adharno']);
    $pancard = strtoupper(trim($_POST['pancard'])); // Convert to uppercase

    $stmt = $con->prepare("UPDATE agents SET name=?, father_name=?, qualification=?, mobile_no=?, email_id=?, address=?, city=?, state=?, adharno=?, pancard=?, message=? WHERE id=?");
    $stmt->bind_param("sssssssssssi", $name, $father_name, $qualification, $mobile_no, $email_id, $address, $city, $state, $adharno, $pancard, $message, $id);

    if ($stmt->execute()) {
        header("Location: agentlist.php?success=updated");
        exit();
    } else {
        $error = "❌ Error updating agent: " . htmlspecialchars($stmt->error);
    }
    $stmt->close();
}

// Fetch agent details from DB to populate the form (after update or on first load)
$stmt = $con->prepare("SELECT * FROM agents WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    $agent = $result->fetch_assoc();
} else {
    echo "<div class='alert alert-danger text-center mt-5'>Agent not found!</div>";
    exit;
}
$stmt->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Edit Agent</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet" />
<style>
    body {
        background: #f4f6f8;
        min-height: 100vh;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 20px;
    }
    .edit-agent-form {
        background: #fff;
        padding: 30px;
        border-radius: 12px;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        width: 100%;
        max-width: 600px;
        position: relative;
    }
    .edit-agent-form h3 {
        margin-bottom: 25px;
        color: #0d6efd;
        font-weight: 700;
        text-align: center;
    }
    .form-control, textarea {
        margin-bottom: 15px;
        border-radius: 8px;
        border: 1px solid #ced4da;
        padding: 12px 15px;
        font-size: 1rem;
    }
    textarea {
        min-height: 80px;
        resize: vertical;
    }
    .btn-primary {
        width: 100%;
        font-weight: 600;
        font-size: 1.1rem;
        padding: 12px;
        border-radius: 10px;
        transition: background-color 0.3s ease;
    }
    .btn-primary:hover {
        background-color: #0b5ed7;
    }
    .logout-btn {
        position: absolute;
        top: 20px;
        right: 20px;
        font-weight: 600;
        border-radius: 10px;
        padding: 6px 16px;
        font-size: 0.9rem;
    }
    .input-icon {
        position: relative;
    }
    .input-icon > .bi {
        position: absolute;
        left: 12px;
        top: 50%;
        transform: translateY(-50%);
        color: #6c757d;
        font-size: 1.2rem;
    }
    .input-icon > input,
    .input-icon > textarea {
        padding-left: 40px !important;
    }
    @media (max-width: 576px) {
        .edit-agent-form {
            padding: 20px;
        }
    }
</style>
</head>
<body>
<form method="POST" class="edit-agent-form" novalidate>
    <a href="logout.php" class="btn btn-outline-danger logout-btn">
        <i class="bi bi-box-arrow-right"></i> Logout
    </a>

    <h3>Edit Agent</h3>

    <?php if($error): ?>
        <div class="alert alert-danger text-center"><?= $error ?></div>
    <?php endif; ?>

    <input type="hidden" name="id" value="<?= $id ?>" />

    <div class="input-icon">
        <i class="bi bi-person-fill"></i>
        <input type="text" name="name" class="form-control" placeholder="Name" value="<?= htmlspecialchars($agent['name'] ?? '') ?>" required autofocus />
    </div>

    <div class="input-icon">
        <i class="bi bi-person-badge"></i>
        <input type="text" name="father_name" class="form-control" placeholder="Father's Name" value="<?= htmlspecialchars($agent['father_name'] ?? '') ?>" />
    </div>

    <div class="input-icon">
        <i class="bi bi-mortarboard-fill"></i>
        <input type="text" name="qualification" class="form-control" placeholder="Qualification" value="<?= htmlspecialchars($agent['qualification'] ?? '') ?>" />
    </div>

    <div class="input-icon">
        <i class="bi bi-telephone-fill"></i>
        <input type="tel" name="mobile_no" class="form-control" placeholder="Mobile No" value="<?= htmlspecialchars($agent['mobile_no'] ?? '') ?>" required pattern="\d{10,15}" title="Enter valid mobile number" />
    </div>

    <div class="input-icon">
        <i class="bi bi-envelope-fill"></i>
        <input type="email" name="email_id" class="form-control" placeholder="Email ID" value="<?= htmlspecialchars($agent['email_id'] ?? '') ?>" required />
    </div>

    <div class="input-icon">
        <i class="bi bi-credit-card-2-front-fill"></i>
        <input type="text" name="adharno" class="form-control" placeholder="Aadhar Number" value="<?= htmlspecialchars($agent['adharno'] ?? '') ?>" required pattern="\d{12}" title="Enter 12 digit Aadhar Number" />
    </div>

    <div class="input-icon">
        <i class="bi bi-file-earmark-person-fill"></i>
        <input type="text" name="pancard" class="form-control" placeholder="Pancard Number" value="<?= htmlspecialchars($agent['pancard'] ?? '') ?>" required pattern="[A-Z]{5}[0-9]{4}[A-Z]{1}" title="Enter valid Pancard Number" />
    </div>

    <div class="input-icon">
        <i class="bi bi-geo-alt-fill"></i>
        <textarea name="address" class="form-control" placeholder="Address"><?= htmlspecialchars($agent['address'] ?? '') ?></textarea>
    </div>

    <div class="input-icon">
        <i class="bi bi-building"></i>
        <input type="text" name="city" class="form-control" placeholder="City" value="<?= htmlspecialchars($agent['city'] ?? '') ?>" />
    </div>

    <div class="input-icon">
        <i class="bi bi-flag-fill"></i>
        <input type="text" name="state" class="form-control" placeholder="State" value="<?= htmlspecialchars($agent['state'] ?? '') ?>" />
    </div>

    <div class="input-icon">
        <i class="bi bi-chat-left-text-fill"></i>
        <textarea name="message" class="form-control" placeholder="Message"><?= htmlspecialchars($agent['message'] ?? '') ?></textarea>
    </div>

    <button type="submit" class="btn btn-primary mt-3">
        <i class="bi bi-save-fill"></i> Update
    </button>
</form>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
