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

require_once "../configs.php";

/* ===========================================================
   MOVE SERVICE UP / DOWN
=========================================================== */
if (isset($_GET['move'], $_GET['id'])) {
    $id  = intval($_GET['id']);
    $dir = $_GET['move']; // up | down

    $c = $conn->prepare("SELECT id, position FROM dashboard_services WHERE id=?");
    $c->bind_param("i",$id);
    $c->execute();
    $cur = $c->get_result()->fetch_assoc();
    $c->close();

    if ($cur) {
        if ($dir === 'up') {
            $q = $conn->prepare("
                SELECT id, position FROM dashboard_services
                WHERE position < ?
                ORDER BY position DESC LIMIT 1
            ");
        } else {
            $q = $conn->prepare("
                SELECT id, position FROM dashboard_services
                WHERE position > ?
                ORDER BY position ASC LIMIT 1
            ");
        }

        $q->bind_param("i",$cur['position']);
        $q->execute();
        $swap = $q->get_result()->fetch_assoc();
        $q->close();

        if ($swap) {
            $conn->begin_transaction();

            $u1 = $conn->prepare("UPDATE dashboard_services SET position=? WHERE id=?");
            $u1->bind_param("ii",$swap['position'],$cur['id']);
            $u1->execute();
            $u1->close();

            $u2 = $conn->prepare("UPDATE dashboard_services SET position=? WHERE id=?");
            $u2->bind_param("ii",$cur['position'],$swap['id']);
            $u2->execute();
            $u2->close();

            $conn->commit();
        }
    }

    header("Location: manage_services.php");
    exit();
}

/* ===========================================================
   DELETE SERVICE
=========================================================== */
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $d = $conn->prepare("DELETE FROM dashboard_services WHERE id=?");
    $d->bind_param("i",$id);
    $d->execute();
    header("Location: manage_services.php");
    exit();
}

/* ===========================================================
   TOGGLE SERVICE
=========================================================== */
if (isset($_GET['toggle'], $_GET['id'])) {
    $id = intval($_GET['id']);
    $q = $conn->query("SELECT status FROM dashboard_services WHERE id=$id");
    $row = $q->fetch_assoc();
    $new = ($row['status']==='on') ? 'off' : 'on';

    $t = $conn->prepare("UPDATE dashboard_services SET status=? WHERE id=?");
    $t->bind_param("si",$new,$id);
    $t->execute();

    header("Location: manage_services.php");
    exit();
}

/* ===========================================================
   EDIT SERVICE (SAVE)
=========================================================== */
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['edit_id'])) {

    $e = $conn->prepare("
        UPDATE dashboard_services 
        SET service_name=?, icon=?, link=? 
        WHERE id=?
    ");
    $e->bind_param(
        "sssi",
        $_POST['edit_name'],
        $_POST['edit_icon'],
        $_POST['edit_link'],
        $_POST['edit_id']
    );
    $e->execute();

    header("Location: manage_services.php");
    exit();
}

/* ===========================================================
   ADD SERVICE
=========================================================== */
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['service_name']) && empty($_POST['edit_id'])) {

    $p = $conn->query("SELECT MAX(position) maxp FROM dashboard_services");
    $pos = ($r=$p->fetch_assoc()) ? intval($r['maxp'])+1 : 1;

    $a = $conn->prepare("
        INSERT INTO dashboard_services (service_name, icon, link, status, position)
        VALUES (?,?,?,'on',?)
    ");
    $a->bind_param("sssi", $_POST['service_name'], $_POST['service_icon'], $_POST['service_link'], $pos);
    $a->execute();

    header("Location: manage_services.php");
    exit();
}

/* ===========================================================
   FETCH SERVICES
=========================================================== */
$services = $conn->query("
    SELECT * FROM dashboard_services
    ORDER BY position ASC
");

/* ===========================================================
   FETCH EDIT ROW IF NEEDED
=========================================================== */
$editRow = null;
if (isset($_GET['edit'])) {
    $id = intval($_GET['edit']);
    $editRow = $conn->query("SELECT * FROM dashboard_services WHERE id=$id")->fetch_assoc();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Manage Dashboard Services</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body{background:#001f33;color:white;font-family:Arial;padding:20px;}
.box{background:#003d66;padding:20px;border-radius:12px;max-width:900px;margin:auto;}
table{width:100%;border-collapse:collapse;margin-top:15px;}
td,th{padding:10px;border-bottom:1px solid #005580;}
a.btn{padding:6px 12px;background:deepskyblue;color:#002;text-decoration:none;border-radius:6px;font-weight:bold;}
.off{background:#dc2626!important;color:white!important;}
.delete{background:#ef4444!important;color:white!important;}
.edit{background:#f59e0b!important;color:#000!important;}
.move{background:#22c55e!important;color:#002!important;}
.add-form{margin-top:20px;padding:15px;background:#002f4d;border-radius:10px;}
input{width:100%;padding:10px;border-radius:8px;border:1px solid #0077aa;margin-bottom:10px;}
button{padding:10px 20px;background:deepskyblue;color:#002;border:none;border-radius:6px;font-weight:bold;}
</style>
</head>
<body>

<div class="box">
<h2>Manage Dashboard Services</h2>

<table>
<tr>
<th>#</th>
<th>Icon</th>
<th>Service</th>
<th>Link</th>
<th>Status</th>
<th>Order</th>
<th>Actions</th>
</tr>

<?php while($s=$services->fetch_assoc()): ?>
<tr>
<td><?= $s['position'] ?></td>
<td><?= htmlspecialchars($s['icon']) ?></td>
<td><?= htmlspecialchars($s['service_name']) ?></td>
<td><?= htmlspecialchars($s['link']) ?></td>
<td><?= strtoupper($s['status']) ?></td>
<td>
<a class="btn move" href="?move=up&id=<?= $s['id'] ?>">↑</a>
<a class="btn move" href="?move=down&id=<?= $s['id'] ?>">↓</a>
</td>
<td>
<a class="btn <?=($s['status']=='off'?'off':'')?>" href="?toggle=1&id=<?=$s['id']?>">Toggle</a>
<a class="btn edit" href="?edit=<?=$s['id']?>">Edit</a>
<a class="btn delete" onclick="return confirm('Delete service?')" href="?delete=<?=$s['id']?>">Delete</a>
</td>
</tr>
<?php endwhile; ?>
</table>

<?php if($editRow): ?>
<div class="add-form">
<h3>Edit Service</h3>
<form method="post">
<input type="hidden" name="edit_id" value="<?= $editRow['id'] ?>">
<input name="edit_name" value="<?= htmlspecialchars($editRow['service_name']) ?>" required>
<input name="edit_icon" value="<?= htmlspecialchars($editRow['icon']) ?>" required>
<input name="edit_link" value="<?= htmlspecialchars($editRow['link']) ?>" required>
<button>Save Changes</button>
</form>
</div>
<?php endif; ?>

<div class="add-form">
<h3>Add New Service</h3>
<form method="post">
<input name="service_name" placeholder="Service Name" required>
<input name="service_icon" placeholder="FontAwesome Icon e.g fa-id-card" required>
<input name="service_link" placeholder="Page link" required>
<button>Add Service</button>
</form>
</div>

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