<?php
require_once '../includes/config.php';
requireAdmin();
$db = getDB();

// Auto-create table
try {
    $db->exec("CREATE TABLE IF NOT EXISTS currencies (
        id INT AUTO_INCREMENT PRIMARY KEY,
        code VARCHAR(10) NOT NULL UNIQUE,
        name VARCHAR(100) NOT NULL,
        symbol VARCHAR(10) NOT NULL,
        rate DECIMAL(15,6) NOT NULL DEFAULT 1.000000,
        is_active TINYINT(1) DEFAULT 1,
        is_default TINYINT(1) DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");
    $cnt = $db->query("SELECT COUNT(*) FROM currencies")->fetchColumn();
    if ($cnt == 0) {
        $ins = [
            ['BDT','Bangladeshi Taka','৳',1.000000,1,1],
            ['USD','US Dollar','$',0.009091,1,0],
            ['EUR','Euro','€',0.008403,1,0],
            ['GBP','British Pound','£',0.007194,1,0],
            ['SAR','Saudi Riyal','SR',0.034091,1,0],
            ['AED','UAE Dirham','AED',0.033397,1,0],
            ['MYR','Malaysian Ringgit','RM',0.042254,1,0],
            ['KWD','Kuwaiti Dinar','KD',0.002792,1,0],
            ['QAR','Qatari Riyal','QR',0.033112,1,0],
            ['OMR','Omani Rial','OMR',0.003497,1,0],
            ['BHD','Bahraini Dinar','BD',0.003427,1,0],
            ['INR','Indian Rupee','Rs',0.757576,1,0],
            ['PKR','Pakistani Rupee','PKR',2.531646,1,0],
            ['SGD','Singapore Dollar','SGD',0.012195,1,0],
            ['AUD','Australian Dollar','AUD',0.013966,1,0],
            ['CAD','Canadian Dollar','CAD',0.012579,1,0],
            ['JPY','Japanese Yen','JPY',1.388889,1,0],
            ['CNY','Chinese Yuan','CNY',0.065789,1,0],
            ['TRY','Turkish Lira','TRY',0.327869,1,0],
            ['NGN','Nigerian Naira','NGN',14.492754,1,0],
            ['KES','Kenyan Shilling','Ksh',1.176471,1,0],
            ['ZAR','South African Rand','ZAR',0.166667,1,0],
            ['NPR','Nepalese Rupee','NPR',1.212121,1,0],
            ['LKR','Sri Lankan Rupee','LKR',2.941176,1,0],
            ['PHP','Philippine Peso','PHP',0.534759,1,0],
            ['IDR','Indonesian Rupiah','IDR',148.148148,1,0],
            ['EGP','Egyptian Pound','EGP',0.454545,1,0],
            ['BRL','Brazilian Real','BRL',0.050505,1,0],
        ];
        $s = $db->prepare("INSERT IGNORE INTO currencies (code,name,symbol,rate,is_active,is_default) VALUES (?,?,?,?,?,?)");
        foreach ($ins as $r) $s->execute($r);
    }
    try { $db->exec("ALTER TABLE users ADD COLUMN preferred_currency VARCHAR(10) DEFAULT 'BDT'"); } catch(Exception $e2) {}
} catch(Exception $e) {}

$msg = null;
if (isset($_GET['ok'])) $msg = ['ok'=>true,'text'=>'✅ Saved successfully!'];

// Handle POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'toggle') {
        $id  = intval($_POST['id'] ?? 0);
        $val = intval($_POST['val'] ?? 0);
        $db->prepare("UPDATE currencies SET is_active=? WHERE id=? AND is_default=0")->execute([$val,$id]);
        header('Content-Type: application/json');
        echo json_encode(['success'=>true]); exit;
    }
    if ($action === 'add') {
        $code=$_POST['code']??''; $name=$_POST['name']??''; $sym=$_POST['symbol']??'';
        $rate=floatval($_POST['rate']??0); $act=intval($_POST['is_active']??1);
        if ($code&&$name&&$sym&&$rate>0) {
            try {
                $db->prepare("INSERT INTO currencies (code,name,symbol,rate,is_active) VALUES (?,?,?,?,?)")
                   ->execute([strtoupper($code),$name,$sym,$rate,$act]);
                $msg=['ok'=>true,'text'=>strtoupper($code).' added!'];
                header('Location: currencies.php?ok=1'); exit;
            } catch(Exception $e) { $msg=['ok'=>false,'text'=>'Code already exists!']; }
        } else { $msg=['ok'=>false,'text'=>'All fields required!']; }
    }
    if ($action === 'edit') {
        $id=intval($_POST['id']??0); $name=$_POST['name']??''; $sym=$_POST['symbol']??'';
        $rate=floatval($_POST['rate']??0); $act=intval($_POST['is_active']??1);
        $db->prepare("UPDATE currencies SET name=?,symbol=?,rate=?,is_active=? WHERE id=?")->execute([$name,$sym,$rate,$act,$id]);
        $msg=['ok'=>true,'text'=>'Updated successfully!'];
        header('Location: currencies.php?ok=1'); exit;
    }
    if ($action === 'delete') {
        $db->prepare("DELETE FROM currencies WHERE id=? AND is_default=0")->execute([intval($_POST['id']??0)]);
        $msg=['ok'=>true,'text'=>'Deleted!'];
        header('Location: currencies.php?ok=1'); exit;
    }
    if ($action === 'set_default') {
        $code=strtoupper($_POST['code']??'');
        $db->exec("UPDATE currencies SET is_default=0");
        $db->prepare("UPDATE currencies SET is_default=1 WHERE code=?")->execute([$code]);
        $msg=['ok'=>true,'text'=>"$code set as default!"];
        header('Location: currencies.php?ok=1'); exit;
    }
}

$currencies = $db->query("SELECT * FROM currencies ORDER BY is_default DESC, code")->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Currencies - Admin</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<link rel="stylesheet" href="../assets/css/admin.css">
<style>
.page-wrap{padding:24px}
.pg-title{font-size:20px;font-weight:800;color:var(--dark);margin-bottom:4px;display:flex;align-items:center;gap:8px}
.pg-sub{font-size:13px;color:#888;margin-bottom:18px}
.card{background:white;border-radius:12px;box-shadow:0 2px 10px rgba(0,0,0,0.06);margin-bottom:18px;overflow:hidden}
.card-h{padding:13px 18px;border-bottom:1px solid #f5f5f5;font-size:14px;font-weight:700;color:var(--dark);display:flex;align-items:center;gap:8px}
.card-b{padding:18px}
.alert{padding:10px 16px;border-radius:10px;font-size:13px;font-weight:600;margin-bottom:14px}
.alert-ok{background:#f0fff4;color:#276749;border:1px solid #c6f6d5}
.alert-err{background:#fff5f5;color:#c53030;border:1px solid #fed7d7}
.frow{display:grid;grid-template-columns:repeat(auto-fill,minmax(120px,1fr));gap:10px;margin-bottom:12px}
.fg{display:flex;flex-direction:column;gap:4px}
.fg label{font-size:12px;font-weight:600;color:#555}
.fg input,.fg select{padding:9px 11px;border:2px solid #e8ecf4;border-radius:9px;font-size:13px;outline:none;width:100%}
.fg input:focus,.fg select:focus{border-color:var(--primary)}
.btn{padding:9px 16px;border:none;border-radius:9px;font-size:13px;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;gap:6px}
.btn-primary{background:var(--primary);color:white}
.btn-sm{padding:5px 11px;font-size:12px;border-radius:7px;cursor:pointer;border:none;font-weight:600}
.btn-edit{background:#ebf8ff;color:#2b6cb0}
.btn-del{background:#fff5f5;color:#e53e3e}
.btn-def{background:#f0fff4;color:#276749}
.btn-gray{background:#f5f5f5;color:#333}
table{width:100%;border-collapse:collapse}
th{padding:9px 12px;text-align:left;font-size:11px;color:#888;font-weight:700;text-transform:uppercase;border-bottom:2px solid #f5f5f5;white-space:nowrap}
td{padding:10px 12px;border-bottom:1px solid #f9f9f9;font-size:13px;vertical-align:middle}
tr:last-child td{border:none}
tr:hover td{background:#fafbff}
.badge{display:inline-block;padding:3px 9px;border-radius:20px;font-size:11px;font-weight:700}
.b-def{background:#fef3c7;color:#92400e}
.sym{font-size:15px;font-weight:800;color:var(--primary);min-width:30px;display:inline-block}
.tog{width:38px;height:22px;background:#ddd;border-radius:20px;position:relative;cursor:pointer;transition:0.3s;border:none;display:inline-block;vertical-align:middle;flex-shrink:0}
.tog.on{background:#38a169}
.tok{width:18px;height:18px;background:white;border-radius:50%;position:absolute;top:2px;left:2px;transition:0.3s;box-shadow:0 1px 3px rgba(0,0,0,0.2);pointer-events:none}
.tog.on .tok{left:18px}

/* MODAL */
.modal-overlay{display:none;position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.55);z-index:99999}
.modal-overlay.show{display:flex;align-items:center;justify-content:center}
.modal-box{background:white;border-radius:14px;padding:24px;width:92%;max-width:440px;box-shadow:0 20px 60px rgba(0,0,0,0.25)}
.modal-box h3{font-size:16px;font-weight:800;margin-bottom:16px;color:var(--dark);display:flex;align-items:center;gap:8px}
.modal-frow{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:10px}
.gap-btn{display:flex;gap:10px;margin-top:6px}
</style>
</head>
<body>
<?php include '../includes/admin_sidebar.php'; ?>

<div class="main">
<div class="topbar">
    <div class="topbar-left">
        <button class="menu-toggle" onclick="openSidebar()"><i class="fas fa-bars"></i></button>
        <span class="topbar-title">Currency Management</span>
    </div>
</div>

<div class="page-wrap">
<div class="pg-title"><i class="fas fa-coins" style="color:var(--secondary)"></i> Currency Management</div>
<div class="pg-sub">Set exchange rates — 1 BDT = how much of each currency</div>

<?php if ($msg): ?>
<div class="alert <?= $msg['ok']?'alert-ok':'alert-err' ?>"><?= $msg['ok']?'✅':'❌' ?> <?= htmlspecialchars($msg['text']) ?></div>
<?php endif; ?>

<!-- Add -->
<div class="card">
    <div class="card-h"><i class="fas fa-plus-circle" style="color:#38a169"></i> Add New Currency</div>
    <div class="card-b">
        <form method="POST">
            <input type="hidden" name="action" value="add">
            <div class="frow">
                <div class="fg"><label>Code (USD)</label><input name="code" placeholder="USD" maxlength="10" required></div>
                <div class="fg"><label>Name</label><input name="name" placeholder="US Dollar" required></div>
                <div class="fg"><label>Symbol ($)</label><input name="symbol" placeholder="$" maxlength="10" required></div>
                <div class="fg"><label>Rate (1 BDT=?)</label><input type="number" name="rate" placeholder="0.009091" step="0.000001" min="0.000001" required></div>
                <div class="fg"><label>Status</label>
                    <select name="is_active"><option value="1">Active</option><option value="0">Inactive</option></select>
                </div>
            </div>
            <button type="submit" class="btn btn-primary"><i class="fas fa-plus"></i> Add</button>
        </form>
    </div>
</div>

<!-- List -->
<div class="card">
    <div class="card-h"><i class="fas fa-list"></i> All Currencies (<?= count($currencies) ?>)</div>
    <div style="overflow-x:auto">
    <table>
        <thead><tr>
            <th>Symbol</th><th>Code</th><th>Name</th>
            <th>1 BDT =</th><th>100 BDT =</th>
            <th>Active</th><th>Default</th><th>Action</th>
        </tr></thead>
        <tbody>
        <?php foreach($currencies as $c): ?>
        <tr>
            <td><span class="sym"><?= htmlspecialchars($c['symbol']) ?></span></td>
            <td><strong><?= $c['code'] ?></strong></td>
            <td><?= htmlspecialchars($c['name']) ?></td>
            <td style="font-family:monospace;font-size:12px"><?= rtrim(rtrim(number_format($c['rate'],6),'0'),'.') ?></td>
            <td><?= htmlspecialchars($c['symbol']) ?><?= number_format(100*$c['rate'],2) ?></td>
            <td>
                <?php if($c['is_default']): ?>
                    <span class="badge" style="background:#f0fff4;color:#276749">Always On</span>
                <?php else: ?>
                    <button class="tog <?= $c['is_active']?'on':'' ?>" id="tog<?= $c['id'] ?>"
                        onclick="doTog(<?= $c['id'] ?>,<?= $c['is_active']?0:1 ?>,this)">
                        <div class="tok"></div></button>
                <?php endif; ?>
            </td>
            <td>
                <?php if($c['is_default']): ?>
                    <span class="badge b-def">⭐ Default</span>
                <?php else: ?>
                    <form method="POST" style="display:inline">
                        <input type="hidden" name="action" value="set_default">
                        <input type="hidden" name="code" value="<?= $c['code'] ?>">
                        <button type="submit" class="btn-sm btn-def">Set Default</button>
                    </form>
                <?php endif; ?>
            </td>
            <td>
                <div style="display:flex;gap:6px;align-items:center">
                    <button class="btn-sm btn-edit"
                        data-id="<?= $c['id'] ?>"
                        data-code="<?= htmlspecialchars($c['code'],ENT_QUOTES) ?>"
                        data-sym="<?= htmlspecialchars($c['symbol'],ENT_QUOTES) ?>"
                        data-name="<?= htmlspecialchars($c['name'],ENT_QUOTES) ?>"
                        data-rate="<?= $c['rate'] ?>"
                        data-active="<?= $c['is_active'] ?>"
                        onclick="doEdit(this)">
                        <i class="fas fa-edit"></i> Edit
                    </button>
                    <?php if(!$c['is_default']): ?>
                    <form method="POST" onsubmit="return confirm('Delete <?= $c['code'] ?>?')" style="display:inline">
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="id" value="<?= $c['id'] ?>">
                        <button type="submit" class="btn-sm btn-del"><i class="fas fa-trash"></i></button>
                    </form>
                    <?php endif; ?>
                </div>
            </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    </div>
</div>

<!-- Guide -->
<div class="card">
    <div class="card-h">💡 Rate Guide</div>
    <div class="card-b" style="font-size:13px;color:#555;line-height:1.9">
        <p><strong>Rate</strong> = 1 BDT এ কত [currency]</p>
        <p>Example: 1 USD = 110 BDT → rate = 1÷110 = <strong>0.009091</strong></p>
        <p>Example: 1 SAR = 29 BDT → rate = 1÷29 = <strong>0.034483</strong></p>
        <p>Example: 1 OMR = 286 BDT → rate = 1÷286 = <strong>0.003497</strong></p>
    </div>
</div>

</div><!-- page-wrap -->
</div><!-- main -->

<!-- Edit Modal -->
<div class="modal-overlay" id="editOverlay" onclick="if(event.target===this)closeEdit()">
    <div class="modal-box">
        <h3><i class="fas fa-edit" style="color:var(--primary)"></i> Edit Currency</h3>
        <form method="POST">
            <input type="hidden" name="action" value="edit">
            <input type="hidden" name="id" id="mId">
            <div class="modal-frow">
                <div class="fg"><label>Code</label><input id="mCode" readonly style="background:#f8f8f8;color:#999"></div>
                <div class="fg"><label>Symbol</label><input name="symbol" id="mSym" required></div>
            </div>
            <div class="fg" style="margin-bottom:10px"><label>Name</label><input name="name" id="mName" required></div>
            <div class="fg" style="margin-bottom:10px">
                <label>Rate (1 BDT = how much?)</label>
                <input type="number" name="rate" id="mRate" step="0.000001" min="0.000001" required>
            </div>
            <div class="fg" style="margin-bottom:16px"><label>Status</label>
                <select name="is_active" id="mActive">
                    <option value="1">Active</option>
                    <option value="0">Inactive</option>
                </select>
            </div>
            <div class="gap-btn">
                <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save Changes</button>
                <button type="button" class="btn btn-gray" onclick="closeEdit()">Cancel</button>
            </div>
        </form>
    </div>
</div>

<script>
function doEdit(btn) {
    document.getElementById('mId').value     = btn.dataset.id;
    document.getElementById('mCode').value   = btn.dataset.code;
    document.getElementById('mSym').value    = btn.dataset.sym;
    document.getElementById('mName').value   = btn.dataset.name;
    document.getElementById('mRate').value   = btn.dataset.rate;
    document.getElementById('mActive').value = btn.dataset.active;
    document.getElementById('editOverlay').classList.add('show');
}
function closeEdit() {
    document.getElementById('editOverlay').classList.remove('show');
}
function doTog(id, newVal, btn) {
    fetch('currencies.php', {
        method:'POST',
        headers:{'Content-Type':'application/x-www-form-urlencoded'},
        body:'action=toggle&id='+id+'&val='+newVal
    }).then(r=>r.json()).then(d=>{
        if(d.success){
            btn.classList.toggle('on', newVal===1);
            btn.onclick = function(){ doTog(id, newVal===1?0:1, btn); };
        }
    });
}
</script>
</body>
</html>
