<?php 
session_start();
if(!isset($_SESSION['SESS_ADMINLOGGEDIN'])) {
    header("Location: " . $config_basedir."../admin/adminlogin.php");
    exit;
}

require_once("header.php");

// DELETE currency
if (isset($_GET['del'])) {
    $stmt = $pdo->prepare("DELETE FROM currencies WHERE id = :id");
    $stmt->execute([':id' => $_GET['del']]);
    echo "<div class='alert alert-success'>✅ Currency deleted successfully!</div>";
}

// ADD currency
if (isset($_POST['add_cur'])) {
    $stmt = $pdo->prepare("INSERT INTO currencies (cur_name, cur_shot_name, cur_symbol, cur_rate, date) 
                           VALUES (:cur_name, :cur_shot_name, :cur_symbol, :cur_rate, :date)");
    $stmt->execute([
        ':cur_name' => htmlspecialchars($_POST['cur_name']),
        ':cur_shot_name' => strtoupper(substr($_POST['cur_shot_name'], 0, 3)), // force 3 letters
        ':cur_symbol' => htmlspecialchars($_POST['cur_symbol']),
        ':cur_rate' => htmlspecialchars($_POST['cur_rate']),
        ':date' => htmlspecialchars($_POST['date'])
    ]);
    echo "<div class='alert alert-success'>✅ Currency added successfully!</div>";
}

// UPDATE currency
if (isset($_POST['edit_currency'])) {
    $stmt = $pdo->prepare("UPDATE currencies SET 
                            cur_name = :cur_name, 
                            cur_shot_name = :cur_shot_name, 
                            cur_symbol = :cur_symbol, 
                            cur_rate = :cur_rate, 
                            date = :date 
                            WHERE id = :id");
    $stmt->execute([
        ':cur_name' => htmlspecialchars($_POST['cur_name']),
        ':cur_shot_name' => strtoupper(substr($_POST['cur_shot_name'], 0, 3)), // force 3 letters
        ':cur_symbol' => htmlspecialchars($_POST['cur_symbol']),
        ':cur_rate' => htmlspecialchars($_POST['cur_rate']),
        ':date' => htmlspecialchars($_POST['date']),
        ':id' => $_POST['id']
    ]);
    echo "<div class='alert alert-success'>✅ Currency updated successfully!</div>";
}

// FIX short names & remove duplicates
if (isset($_POST['fix_currencies'])) {
    try {
        // Step 1: Normalize short names to 3 letters
        $pdo->exec("UPDATE currencies SET cur_shot_name = UPPER(LEFT(cur_shot_name, 3))");

        // Step 2: Remove duplicates (keep lowest ID)
        $sql = "
            DELETE c1 FROM currencies c1
            INNER JOIN currencies c2 
            ON c1.cur_shot_name = c2.cur_shot_name 
            AND c1.id > c2.id
        ";
        $pdo->exec($sql);

        echo "<div class='alert alert-success'>✅ Currency short names fixed & duplicates removed!</div>";
    } catch (Exception $e) {
        echo "<div class='alert alert-danger'>❌ Error: " . $e->getMessage() . "</div>";
    }
}
?>

<div class="main-panel">
    <div class="content bg-light">
        <div class="page-inner">
            <h1 class="title1 text-dark">Manage Currencies</h1>

            <!-- Fix Button -->
            <form method="POST" class="mb-3">
                <button type="submit" name="fix_currencies" class="btn btn-warning">
                    🛠 Fix Short Names & Remove Duplicates
                </button>
            </form>

            <!-- Currency List -->
            <?php
            $stmt = $pdo->query("SELECT * FROM currencies ORDER BY id ASC");
            while ($row = $stmt->fetch()) {
                echo "<form method='POST' class='border p-3 mb-3 bg-white rounded shadow-sm'>
                    <input type='hidden' name='id' value='". $row['id'] ."'/>    

                    <label>Currency Name</label>
                    <input type='text' class='form-control mb-2' name='cur_name' value='". $row['cur_name'] ."' required/> 

                    <label>Short Name</label>
                    <input type='text' class='form-control mb-2' name='cur_shot_name' value='". $row['cur_shot_name'] ."' required/> 

                    <label>Symbol</label>
                    <input type='text' class='form-control mb-2' name='cur_symbol' value='". $row['cur_symbol'] ."' required/> 

                    <label>Rate</label>
                    <input type='text' class='form-control mb-2' name='cur_rate' value='". $row['cur_rate'] ."' required/> 

                    <input type='hidden' name='date' value='". date("jS F Y g.iA") ."' />

                    <div class='d-flex justify-content-between'>
                        <a href='currency.php?del=" . $row['id'] . "' class='btn btn-danger'>❌ Delete</a>
                        <button type='submit' class='btn btn-success' name='edit_currency'>💾 Update</button>
                    </div>
                </form>";
            }
            ?>

            <hr>

            <!-- Add Currency -->
            <!--<h3>Add New Currency</h3>-->
            <!--<form method='POST' class='border p-3 bg-white rounded shadow-sm'> -->
            <!--    <input type="hidden" name="date" value="<php echo date("jS F Y g.iA"); ?>" />-->

            <!--    <label>Currency Name</label>-->
            <!--    <input type='text' class='form-control mb-2' name='cur_name' required/>-->

            <!--    <label>Currency Short Name</label>-->
            <!--    <input type='text' class='form-control mb-2' name='cur_shot_name' required/>-->

            <!--    <label>Currency Symbol</label>-->
            <!--    <input type='text' class='form-control mb-2' name='cur_symbol' required/>-->

            <!--    <label>USD Rate</label>-->
            <!--    <input type='text' class='form-control mb-2' name='cur_rate' required/>-->

            <!--    <button type='submit' class='btn btn-primary btn-block' name='add_cur'>➕ Add Currency</button>-->
            <!--</form>-->
        </div>
    </div>
</div>

<?php require("footer.php"); ?>
