<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require('../../mysqli_connect.php');

$display = 5;

$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$start = (isset($_GET['s']) && is_numeric($_GET['s'])) ? (int)$_GET['s'] : 0;

$sort = isset($_GET['sort']) ? $_GET['sort'] : 'location';

switch ($sort) {
    case 'map':  $order_by = 'Map ASC, Location ASC'; break;
    case 'tier': $order_by = 'Tier ASC, Location ASC'; break;
    case 'loot': $order_by = 'Loot_level ASC, Location ASC'; break;
    case 'type': $order_by = 'Type ASC, Location ASC'; break;
    default:     $order_by = 'Location ASC'; break;
}

$where = '';
if (!empty($search)) {
    $safe = mysqli_real_escape_string($dbc, $search);
    $where = "WHERE Location LIKE '%$safe%' OR Map LIKE '%$safe%' OR Type LIKE '%$safe%'";
}

$message = "";
$edit = false;
$form = ['Location'=>'','Map'=>'','Type'=>'','Tier'=>'','Loot_level'=>''];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($_POST['password'] === "HelloKitty123") {

        $location = trim($_POST['location']);
        $map = trim($_POST['map']);
        $type = trim($_POST['type']);
        $tier = trim($_POST['tier']);
        $loot = trim($_POST['loot']);
        $original = $_POST['original_location'] ?? "";

        if ($original !== "") {
            $stmt = $dbc->prepare("UPDATE Arc_Raiders_100 SET Location=?,Map=?,Type=?,Tier=?,Loot_level=? WHERE Location=?");
            $stmt->bind_param("ssssss", $location,$map,$type,$tier,$loot,$original);
            $stmt->execute();
            $message = "Record updated.";
        } else {
            $stmt = $dbc->prepare("INSERT INTO Arc_Raiders_100 (Location,Map,Type,Tier,Loot_level) VALUES (?,?,?,?,?)");
            $stmt->bind_param("sssss", $location,$map,$type,$tier,$loot);
            $stmt->execute();
            $message = "Record added.";
        }
    } else {
        $message = "Incorrect password.";
    }
}

if (isset($_GET['edit'])) {
    $loc = mysqli_real_escape_string($dbc, $_GET['edit']);
    $res = mysqli_query($dbc, "SELECT * FROM Arc_Raiders_100 WHERE Location='$loc'");
    if ($row = mysqli_fetch_assoc($res)) {
        $edit = true;
        foreach ($form as $k => $v) {
            $form[$k] = htmlspecialchars($row[$k]);
        }
    }
}

$total_q = mysqli_query($dbc, "SELECT COUNT(*) FROM Arc_Raiders_100 $where");
$total = mysqli_fetch_array($total_q)[0];
$pages = ceil($total / $display);

if ($start >= $total) $start = 0;

$data_q = mysqli_query($dbc,
    "SELECT Location,Map,Type,Tier,Loot_level
     FROM Arc_Raiders_100
     $where
     ORDER BY $order_by
     LIMIT $start,$display"
);
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Arc Raiders List</title>

<style>
/* ===== BASE ===== */
body{
    font-family: Arial, sans-serif;
    background:#f5f5f5;
    margin:10px;
}

h1{
    text-align:center;
    font-size:1.8rem;
}

/* ===== SEARCH ===== */
.search_con{
    padding:10px;
    border:2px solid #888;
    background:#fff;
    margin-bottom:15px;
}

.search_con form{
    display:flex;
    flex-wrap:wrap;
    gap:10px;
}

.search_con input[type="text"]{
    flex:1;
    min-width:150px;
    padding:10px;
    font-size:16px;
}

.search_con input[type="submit"]{
    padding:10px 15px;
    font-size:16px;
}

/* ===== LAYOUT ===== */
.main-layout{
    display:flex;
    gap:20px;
}

/* ===== PANELS ===== */
.records-panel,
.form_panel{
    background:#fff;
    padding:15px;
    border:2px solid #444;
}

/* desktop */
.records-panel{ flex:2; max-height:80vh; overflow-y:auto; }
.form_panel{ flex:1; }

/* ===== CARDS ===== */
.card{
    background:#fafafa;
    border:1px solid #aaa;
    padding:12px;
    margin-bottom:12px;
    border-radius:8px;
}

.card h3{
    margin-top:0;
}

/* ===== BUTTON ===== */
.edit-btn{
    display:inline-block;
    margin-top:8px;
    padding:8px 12px;
    background:#4CAF50;
    color:white;
    text-decoration:none;
    border-radius:5px;
}

/* ===== FORM ===== */
.form_panel input{
    width:100%;
    padding:10px;
    margin-bottom:10px;
    font-size:16px;
    border:2px solid #444;
    border-radius:5px;
    box-sizing:border-box;
}

.form_panel input[type="submit"]{
    background:#007BFF;
    color:white;
    border:none;
}

/* ===== PAGINATION ===== */
.pagination{
    text-align:center;
    margin-top:10px;
}

/* ===== MOBILE ===== */
@media (max-width: 768px){

    .main-layout{
        flex-direction:column;
    }

    .records-panel,
    .form_panel{
        width:100%;
        max-height:none;
    }

    .edit-btn{
        width:100%;
        text-align:center;
    }

    .search_con input[type="submit"]{
        width:100%;
    }
}
</style>

</head>

<body>

<h1>Arc Raiders List</h1>

<div class="search_con">
<form method="GET">
<input type="text" name="search" value="<?=htmlspecialchars($search)?>" placeholder="Search...">
<input type="submit" value="Search">
</form>
</div>

<div class="main-layout">

<div class="records-panel">

<?php while($row=mysqli_fetch_assoc($data_q)): ?>
<div class="card">
<h3><?=htmlspecialchars($row['Location'])?></h3>
<p><strong>Map:</strong> <?=$row['Map']?></p>
<p><strong>Type:</strong> <?=$row['Type']?></p>
<p><strong>Tier:</strong> <?=$row['Tier']?></p>
<p><strong>Loot:</strong> <?=$row['Loot_level']?></p>

<a class="edit-btn"
href="?edit=<?=urlencode($row['Location'])?>&search=<?=urlencode($search)?>">
Edit
</a>
</div>
<?php endwhile; ?>

<div class="pagination">
<?php
$page = floor($start/$display)+1;

if ($page>1) {
    $prev = $start-$display;
    echo "<a href='?s=$prev&search=$search'>Prev</a> ";
}

echo "Page $page of $pages";

if ($page<$pages) {
    $next = $start+$display;
    echo " <a href='?s=$next&search=$search'>Next</a>";
}
?>
</div>

</div>

<div class="form_panel">

<h2><?= $edit ? "Edit Record" : "Add Record" ?></h2>
<p><?=$message?></p>

<form method="POST">
<input type="hidden" name="original_location" value="<?=$form['Location']?>">

<input type="password" name="password" placeholder="Password" required>
<input type="text" name="location" value="<?=$form['Location']?>" placeholder="Location" required>
<input type="text" name="map" value="<?=$form['Map']?>" placeholder="Map" required>
<input type="text" name="type" value="<?=$form['Type']?>" placeholder="Type" required>
<input type="text" name="tier" value="<?=$form['Tier']?>" placeholder="Tier" required>
<input type="text" name="loot" value="<?=$form['Loot_level']?>" placeholder="Loot Level" required>

<input type="submit" value="<?= $edit ? 'Update' : 'Add' ?>">
</form>

</div>

</div>

</body>
</html>