<?php 
include 'config.php'; 
if(!isset($_SESSION['user_role']) || $_SESSION['user_role'] != 'SuperAdmin') {
    header("Location: dashboard.php");
    exit();
}

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$agency_query = $conn->query("SELECT * FROM agencies WHERE id = $id");

if($agency_query->num_rows == 0) die("Agency not found.");
$agency = $agency_query->fetch_assoc();

// Handle Form Submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST['agency_name'];
    $owner = $_POST['owner_name'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $expiry = $_POST['expiry_date'];
    $status = $_POST['status'];
    $balance = (float)$_POST['balance_due'];
    
    // Limits
    $max_t = (int)$_POST['max_tickets'];
    $max_u = (int)$_POST['max_umrah'];
    $max_p = (int)$_POST['max_posters'];
    
    // Reset Poster Logic
    $reset_sql = "";
    if($_POST['reset_posters'] == 'yes') {
        $reset_sql = ", posters_generated = 0, tickets_used = 0, umrah_used = 0";
    }

    // UPDATE QUERY (11 Placeholders: 10 sets + 1 where ID)
    $sql = "UPDATE agencies SET 
            agency_name=?, 
            owner_name=?, 
            email=?, 
            phone=?, 
            expiry_date=?, 
            status=?, 
            balance_due=?, 
            max_tickets=?, 
            max_umrah=?, 
            max_posters=? 
            $reset_sql 
            WHERE id=?";

    $stmt = $conn->prepare($sql);
    
    // Type string: ssssss d iiii (6 strings, 1 double, 4 integers = 11 total)
    $types = "ssssssdiiri"; // 'd' for balance, 'i' for limits and ID
    // Fixed types string: 11 characters for 11 variables
    $stmt->bind_param("ssssssdiiii", $name, $owner, $email, $phone, $expiry, $status, $balance, $max_t, $max_u, $max_p, $id);
    
    if ($stmt->execute()) {
        // Sync User Login
        $conn->query("UPDATE users SET email='$email', name='$owner' WHERE agency_id=$id AND role='AgencyOwner'");
        header("Location: manage_agencies.php?msg=updated");
        exit();
    } else {
        $error = "Update failed: " . $conn->error;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Edit Agency Authority | <?php echo $agency['agency_name']; ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { --primary: #4e73df; --secondary: #1e293b; --bg-color: #f8f9fc; }
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; }
        body { background-color: var(--bg-color); padding: 40px; }
        .card { background: #fff; padding: 35px; border-radius: 20px; box-shadow: 0 10px 30px rgba(0,0,0,0.05); max-width: 900px; margin: auto; }
        .header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; border-bottom: 2px solid #f1f5f9; padding-bottom: 15px; }
        .form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 25px; }
        .form-group { margin-bottom: 20px; }
        label { display: block; font-size: 12px; font-weight: 700; color: #64748b; margin-bottom: 8px; text-transform: uppercase; }
        input, select { width: 100%; padding: 12px; border: 1px solid #e2e8f0; border-radius: 12px; font-size: 14px; outline: none; transition: 0.3s; }
        input:focus { border-color: var(--primary); box-shadow: 0 0 0 4px rgba(78, 115, 223, 0.1); }
        .btn-save { background: var(--primary); color: #fff; padding: 15px 40px; border: none; border-radius: 12px; cursor: pointer; font-weight: 700; width: 100%; margin-top: 20px; font-size: 16px; }
        .section-title { font-size: 14px; color: var(--primary); font-weight: 700; margin-bottom: 20px; display: flex; align-items: center; gap: 10px; text-transform: uppercase; }
        .section-title hr { flex: 1; border: 0; border-top: 1px solid #eee; }
        .usage-badge { background: #f1f5f9; padding: 5px 10px; border-radius: 6px; font-size: 11px; color: #475569; font-weight: 600; margin-top: 5px; display: inline-block; }
    </style>
</head>
<body>

    <div class="card">
        <div class="header">
            <div>
                <h2 style="color:var(--secondary);"><i class="fas fa-user-shield"></i> Agency Authority</h2>
                <p style="color:#64748b; font-size: 13px;">Modify credentials and monthly limits.</p>
            </div>
            <a href="manage_agencies.php" style="text-decoration:none; color:#64748b;"><i class="fas fa-times"></i></a>
        </div>

        <?php if(isset($error)) echo "<p style='color:red; margin-bottom:20px;'>$error</p>"; ?>

        <form action="" method="POST">
            
            <div class="section-title">Account Details <hr></div>
            <div class="form-grid">
                <div class="form-group">
                    <label>Agency Name</label>
                    <input type="text" name="agency_name" value="<?php echo htmlspecialchars($agency['agency_name']); ?>" required>
                </div>
                <div class="form-group">
                    <label>Owner Name</label>
                    <input type="text" name="owner_name" value="<?php echo htmlspecialchars($agency['owner_name']); ?>" required>
                </div>
                <div class="form-group">
                    <label>Email (Username)</label>
                    <input type="email" name="email" value="<?php echo $agency['email']; ?>" required>
                </div>
                <div class="form-group">
                    <label>Phone</label>
                    <input type="text" name="phone" value="<?php echo $agency['phone']; ?>">
                </div>
            </div>

            <div class="section-title" style="margin-top: 20px;">Subscription & Balance <hr></div>
            <div class="form-grid">
                <div class="form-group">
                    <label>Expiry Date</label>
                    <input type="date" name="expiry_date" value="<?php echo $agency['expiry_date']; ?>" required>
                </div>
                <div class="form-group">
                    <label>Status</label>
                    <select name="status">
                        <option value="Active" <?php echo ($agency['status'] == 'Active' ? 'selected' : ''); ?>>Active</option>
                        <option value="Suspended" <?php echo ($agency['status'] == 'Suspended' ? 'selected' : ''); ?>>Suspended</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Balance Due (PKR)</label>
                    <input type="number" step="0.01" name="balance_due" value="<?php echo $agency['balance_due']; ?>" required>
                </div>
            </div>

            <div class="section-title" style="margin-top: 20px;">Monthly Usage Limits <hr></div>
            <div class="form-grid">
                <div class="form-group">
                    <label>Max Ticket Vouchers</label>
                    <input type="number" name="max_tickets" value="<?php echo $agency['max_tickets']; ?>" required>
                    <span class="usage-badge">Currently Used: <?php echo $agency['tickets_used']; ?></span>
                </div>
                <div class="form-group">
                    <label>Max Umrah Vouchers</label>
                    <input type="number" name="max_umrah" value="<?php echo $agency['max_umrah']; ?>" required>
                    <span class="usage-badge">Currently Used: <?php echo $agency['umrah_used']; ?></span>
                </div>
                <div class="form-group">
                    <label>Max Poster Downloads</label>
                    <input type="number" name="max_posters" value="<?php echo $agency['max_posters']; ?>" required>
                    <span class="usage-badge">Currently Used: <?php echo $agency['posters_generated']; ?></span>
                </div>
                <div class="form-group">
                    <label>Action for New Month</label>
                    <select name="reset_posters">
                        <option value="no">Keep Current Usage counts</option>
                        <option value="yes">RESET ALL USAGE TO 0 NOW</option>
                    </select>
                </div>
            </div>

            <button type="submit" class="btn-save">Update Agency & Limits</button>
        </form>
    </div>

</body>
</html>