<?php
include "includes/db_connect.php";
include "includes/auth.php";
checkAdmin();

// Handle AJAX save/update
if(isset($_POST['action']) && ($_POST['action']=='update' || $_POST['action']=='add')){
    $code = strtoupper($_POST['country_code']);
    $name = $_POST['country_name'];
    $currency = strtoupper($_POST['currency']);
    $status = $_POST['status']=='1'?1:0;

    if($_POST['action']=='update'){
        mysqli_query($conn,"UPDATE countries 
            SET country_name='".mysqli_real_escape_string($conn,$name)."', currency='$currency', status='$status' 
            WHERE country_code='$code'");
    } else { // add
        mysqli_query($conn,"INSERT INTO countries (country_code,country_name,currency_code,status)
            VALUES ('$code','".mysqli_real_escape_string($conn,$name)."','$currency','$status')");
    }

    echo json_encode(['success'=>true]);
    exit;
}

// Fetch countries
$countries_res = mysqli_query($conn,"SELECT * FROM countries ORDER BY country_name");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Manage Countries - Mobex ADR Admin</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">
<style>
body { font-family:'Inter',sans-serif; background:#f0f4f8; margin:0; padding:0; }
header { background:#6366f1; color:#fff; padding:15px 20px; display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; }
header h1 { margin:0; font-size:1.2rem; }
header a { color:#fff; text-decoration:none; font-weight:600; }
.container { max-width:1000px; margin:auto; padding:20px; }
.card { background:#fff; padding:20px; border-radius:12px; box-shadow:0 10px 20px rgba(0,0,0,0.05); margin-bottom:20px; }
h2 { margin-bottom:15px; color:#1f2937; font-weight:700; }
.table-responsive { overflow-x:auto; }
table { width:100%; border-collapse:collapse; }
th, td { padding:12px 10px; text-align:left; font-size:0.9rem; }
thead { background:#f3f4f6; }
tr:hover { background:#f9fafb; }
.status-label { font-weight:600; padding:3px 6px; border-radius:6px; color:#fff; font-size:0.8rem; }
.status-active { background:#2ecc71; }
.status-inactive { background:#e74c3c; }
.input-field { width:100%; padding:6px 10px; border-radius:6px; border:1px solid #ccc; font-size:0.9rem; }
.btn { background:#6366f1; color:#fff; padding:8px 15px; border:none; border-radius:8px; cursor:pointer; font-weight:600; font-size:0.9rem; transition:0.3s; }
.btn:hover { background:#4f46e5; }
@media(max-width:600px){ th, td{font-size:0.8rem; padding:8px 5px;} .btn{padding:6px 10px;font-size:0.8rem;} }
</style>
<script>
function saveCountry(code){
    let name = document.getElementById('name_'+code).value;
    let currency = document.getElementById('currency_'+code).value;
    let status = document.getElementById('status_'+code).checked ? 1 : 0;
    fetch('countries.php',{
        method:'POST',
        headers:{'Content-Type':'application/x-www-form-urlencoded'},
        body:`action=update&country_code=${code}&country_name=${encodeURIComponent(name)}&currency=${encodeURIComponent(currency)}&status=${status}`
    }).then(r=>r.json()).then(data=>{
        if(data.success){
            let label = document.getElementById('label_'+code);
            label.innerText = status?'Active':'Inactive';
            label.className = 'status-label ' + (status?'status-active':'status-inactive');
        }
    });
}

function addCountry(){
    let code = document.getElementById('new_code').value;
    let name = document.getElementById('new_name').value;
    let currency = document.getElementById('new_currency').value;
    let status = document.getElementById('new_status').checked ? 1 : 0;
    if(!code || !name || !currency){ alert("Code, Name and Currency are required"); return; }

    fetch('countries.php',{
        method:'POST',
        headers:{'Content-Type':'application/x-www-form-urlencoded'},
        body:`action=add&country_code=${code}&country_name=${encodeURIComponent(name)}&currency=${encodeURIComponent(currency)}&status=${status}`
    }).then(r=>r.json()).then(data=>{
        if(data.success) location.reload();
    });
}
</script>
</head>
<body>
<?php include "includes/mobex_sidebar.php"; ?>

<div class="container">

<div class="card">
<h2>Add New Country</h2>
<div style="display:flex;gap:10px;flex-wrap:wrap;">
<input type="text" id="new_code" class="input-field" placeholder="Country Code (e.g., GH)">
<input type="text" id="new_name" class="input-field" placeholder="Country Name">
<input type="text" id="new_currency" class="input-field" placeholder="Currency (e.g., GHC)">
<label style="display:flex;align-items:center;gap:5px;"><input type="checkbox" id="new_status" checked> Active</label>
<button class="btn" onclick="addCountry()">Add Country</button>
</div>
</div>

<div class="card">
<h2>Existing Countries</h2>
<div class="table-responsive">
<table>
<thead>
<tr>
<th>Code</th>
<th>Name</th>
<th>Currency</th>
<th>Status</th>
<th>Update</th>
</tr>
</thead>
<tbody>
<?php while($row=mysqli_fetch_assoc($countries_res)): ?>
<tr>
<td><?= $row['country_code'] ?></td>
<td><input type="text" id="name_<?= $row['country_code'] ?>" class="input-field" value="<?= htmlspecialchars($row['country_name']) ?>"></td>
<td><input type="text" id="currency_<?= $row['currency_code'] ?>" class="input-field" value="<?= htmlspecialchars($row['currency_code']) ?>"></td>
<td>
<label id="label_<?= $row['country_code'] ?>" class="status-label <?= $row['status']?'status-active':'status-inactive' ?>"><?= $row['status']?'Active':'Inactive' ?></label>
<label style="display:flex;align-items:center;gap:5px;"><input type="checkbox" id="status_<?= $row['country_code'] ?>" <?= $row['status']?'checked':'' ?>></label>
</td>
<td><button class="btn" onclick="saveCountry('<?= $row['country_code'] ?>')">Save</button></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>
</div>

</div>
</body>
</html>
