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

require_once("header.php");

// ==================== DELETE ====================
if (isset($_GET['del']) && is_numeric($_GET['del'])) {
    $del_id = (int) $_GET['del'];
    $stmt = $pdo->prepare("DELETE FROM testimony WHERE id = :id");
    $stmt->execute([':id' => $del_id]);

    echo "<span style='color:red'>Successfully deleted.
        <meta http-equiv='refresh' content='2; url=admin_control_testimony.php'/>
    </span>";
}

// ==================== ADD ====================
if (isset($_POST['add_testimony'])) {
    $name = htmlspecialchars($_POST['name']);
    $position = htmlspecialchars($_POST['position']);
    $country = htmlspecialchars($_POST['country']);
    $state = htmlspecialchars($_POST['state']);
    $deposit = htmlspecialchars($_POST['deposit']);
    $withdraw = htmlspecialchars($_POST['withdraw']);
    $status = htmlspecialchars($_POST['status']);

    $maxsize = 104857600; 
    $uploadOk = false;
    $Pack_location = "";

    if (isset($_FILES['imgfile']['name']) && $_FILES['imgfile']['name'] != '') {
        $target_dir = "../accounts/upload/testimony/";
        $filename = basename($_FILES["imgfile"]["name"]);
        $target_file = $target_dir . $filename;
        $extension = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
        $extensions_arr = ["jpg", "png", "jpeg", "gif", "jfif"];

        if (in_array($extension, $extensions_arr)) {
            if ($_FILES['imgfile']['size'] > 0 && $_FILES['imgfile']['size'] < $maxsize) {
                if (move_uploaded_file($_FILES["imgfile"]["tmp_name"], $target_file)) {
                    $Pack_location = "accounts/upload/testimony/" . $filename;
                    $uploadOk = true;
                }
            } else {
                echo "<div class='alert alert-danger'>File too large or empty. Max 100MB.</div>";
            }
        } else {
            echo "<div class='alert alert-danger'>Invalid file type.</div>";
        }
    }

    if ($uploadOk) {
        try {
            $stmt = $pdo->prepare("INSERT INTO testimony 
                (name, position, country, state, deposit, withdraw, Pack_location, status) 
                VALUES (:name, :position, :country, :state, :deposit, :withdraw, :Pack_location, :status)");
            $stmt->execute([
                ':name' => $name,
                ':position' => $position,
                ':country' => $country,
                ':state' => $state,
                ':deposit' => $deposit,
                ':withdraw' => $withdraw,
                ':Pack_location' => $Pack_location,
                ':status' => $status
            ]);

            echo "<script>alert('Testimony uploaded successfully!'); window.location.href='';</script>";
        } catch (PDOException $e) {
            echo "<div class='alert alert-danger'>Error: " . $e->getMessage() . "</div>";
        }
    }
}

// ==================== UPDATE ====================
if (isset($_POST['id'])) {
    $id = (int) $_POST['id'];

    // Update content
    if (isset($_POST['update_testimony'])) {
        $name = htmlspecialchars($_POST['name']);
        $position = htmlspecialchars($_POST['position']);
        $country = htmlspecialchars($_POST['country']);
        $state = htmlspecialchars($_POST['state']);
        $deposit = htmlspecialchars($_POST['deposit']);
        $withdraw = htmlspecialchars($_POST['withdraw']);
        $status = (int) $_POST['status'];

        $stmt = $pdo->prepare("UPDATE testimony 
            SET name=?, position=?, country=?, state=?, deposit=?, withdraw=?, status=? WHERE id=?");
        $stmt->execute([$name, $position, $country, $state, $deposit, $withdraw, $status, $id]);

        echo "<script>alert('Testimony updated successfully!'); window.location.href='';</script>";
    }

    // Update photo
    if (isset($_POST['update_photo'])) {
        $maxsize = 104857600; 
        $uploadOk = false;
        $Pack_location = '';

        if (!empty($_FILES["imgfile"]["name"])) {
            $target_dir = "../accounts/upload/testimony/";
            $filename = basename($_FILES["imgfile"]["name"]);
            $target_file = $target_dir . $filename;
            $extension = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
            $extensions_arr = ["jpg", "png", "jpeg", "gif", "jfif"];

            if (in_array($extension, $extensions_arr)) {
                if ($_FILES['imgfile']['size'] > 0 && $_FILES['imgfile']['size'] < $maxsize) {
                    if (move_uploaded_file($_FILES["imgfile"]["tmp_name"], $target_file)) {
                        $Pack_location = "accounts/upload/testimony/" . $filename;
                        $uploadOk = true;
                    }
                }
            }

            if ($uploadOk) {
                $stmt = $pdo->prepare("UPDATE testimony SET Pack_location = ? WHERE id = ?");
                $stmt->execute([$Pack_location, $id]);

                echo "<div class='alert alert-success'>Photo updated!<meta http-equiv='refresh' content='2; url=admin_control_testimony.php' /></div>";
            }
        }
    }
}
?>

<div class="main-panel">
    <div class="content bg-light">
        <div class="page-inner">
            <div class="mt-2 mb-4">
                <h1 class="title1 text-dark">TESTIMONIES</h1>
            </div>

            <?php
            $stmt = $pdo->query("SELECT * FROM testimony ORDER BY id ASC");
            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

            foreach ($rows as $row): ?>
                <div class="message bg-white p-3 mb-3 rounded shadow-sm">
                    <span class="visible-text">
                        <div class="form-group">
                            <label class="form-control">NAME</label>
                            <input type="text" class="form-control bg-light text-dark" value="<?= htmlspecialchars($row['name']) ?>" readonly><br>
                        </div>
                    </span>

                    <span class="hidden-text" style="display:none;">
                        <!-- Update content -->
                        <form method="POST" enctype="multipart/form-data" action="">
                            <input type="hidden" name="id" value="<?= $row['id'] ?>">
                            <div class="form-group"><label class="form-control">NAME</label>
                                <input type="text" name="name" value="<?= htmlspecialchars($row['name']) ?>" class="form-control bg-light text-dark">
                            </div>
                            <div class="form-group"><label class="form-control">POSITION</label>
                                <input type="text" name="position" value="<?= htmlspecialchars($row['position']) ?>" class="form-control bg-light text-dark">
                            </div>
                            <div class="form-group"><label class="form-control">COUNTRY</label>
                                <select id="country-<?= $row['id'] ?>" name="country" class="form-control bg-light text-dark"
                                    data-selected="<?= htmlspecialchars($row['country']) ?>"></select>
                            </div>
                            <div class="form-group"><label class="form-control">STATE</label>
                                <select id="state-<?= $row['id'] ?>" name="state" class="form-control bg-light text-dark"
                                    data-selected="<?= htmlspecialchars($row['state']) ?>"></select>
                            </div>
                            <div class="form-group"><label class="form-control">DEPOSIT</label>
                                <input type="number" name="deposit" value="<?= $row['deposit'] ?>" class="form-control bg-light text-dark">
                            </div>
                            <div class="form-group"><label class="form-control">WITHDRAW</label>
                                <input type="number" name="withdraw" value="<?= $row['withdraw'] ?>" class="form-control bg-light text-dark">
                            </div>
                            <div class="form-group"><label class="form-control">STATUS</label>
                                <select name="status" class="form-control bg-light text-dark">
                                    <option value="1" <?= $row['status']==1?'selected':'' ?>>ACTIVE</option>
                                    <option value="0" <?= $row['status']==0?'selected':'' ?>>INACTIVE</option>
                                </select>
                            </div>

                            <div class="button-group">
                                <a href="admin_control_testimony.php?del=<?= $row['id'] ?>" class="btn btn-danger">DELETE</a>
                                <button type="submit" class="btn btn-success" name="update_testimony">UPDATE</button>
                            </div>
                        </form>

                        <!-- Update photo -->
                        <form method="POST" enctype="multipart/form-data" action="">
                            <input type="hidden" name="id" value="<?= $row['id'] ?>">
                            <div class="form-group">
                                <input type="file" name="imgfile" class="form-control bg-light text-dark" accept="image/*" required>
                                <label class="form-control">
                                    PHOTO
                                    <img src="../<?= htmlspecialchars($row['Pack_location']) ?>" width="40px" height="40px" class="rounded-circle">
                                    <button type="submit" class="btn btn-info" name="update_photo">CHANGE</button>
                                </label>
                            </div>
                        </form>
                        <hr>
                    </span>

                    <span class="btn btn-primary">View More</span>
                </div>
            <?php endforeach; ?>

            <hr>
            <center>ADD NEW TESTIMONY</center>
            <form method="POST" enctype="multipart/form-data" action="">
                <div class="form-group"><label class="form-control">NAME</label>
                    <input type="text" name="name" class="form-control bg-light text-dark" required>
                </div>
                <div class="form-group"><label class="form-control">POSITION</label>
                    <input type="text" name="position" class="form-control bg-light text-dark" required>
                </div>
                <div class="form-group"><label class="form-control">COUNTRY</label>
                    <select id="country" name="country" class="form-control bg-light text-dark" required></select>
                </div>
                <div class="form-group"><label class="form-control">STATE</label>
                    <select id="state" name="state" class="form-control bg-light text-dark" required></select>
                </div>
                <div class="form-group"><label class="form-control">DEPOSIT</label>
                    <input type="number" name="deposit" class="form-control bg-light text-dark" required>
                </div>
                <div class="form-group"><label class="form-control">WITHDRAW</label>
                    <input type="number" name="withdraw" class="form-control bg-light text-dark" required>
                </div>
                <div class="form-group"><label class="form-control">STATUS</label>
                    <select name="status" class="form-control bg-light text-dark" required>
                        <option value="1">ACTIVE</option>
                        <option value="0">INACTIVE</option>
                    </select>
                </div>
                <div class="form-group"><label class="form-control">PHOTO</label>
                    <input type="file" name="imgfile" accept="image/*" class="form-control bg-light text-dark" required>
                </div>
                <button type="submit" class="btn btn-success btn-block" name="add_testimony">ADD TESTIMONY</button>
            </form>
        </div>
    </div>
</div>

<script>
// Country/State script (same as before)
async function safeFetchJSON(path) {
  try { const res = await fetch(path, {cache:"no-store"}); if(!res.ok) throw new Error("HTTP "+res.status); return await res.json(); } 
  catch(e){console.error("Country/state JSON load failed", e); return null;}
}

function populateFromObject(countryStateData, countrySelectId, stateSelectId, selectedCountry="", selectedState="") {
  const countrySelect = document.getElementById(countrySelectId);
  const stateSelect = document.getElementById(stateSelectId);
  if(!countrySelect || !stateSelect) return;
  countrySelect.innerHTML=""; stateSelect.innerHTML="";
  const chooseOpt = document.createElement("option"); chooseOpt.value=""; chooseOpt.textContent="-- Select Country --"; countrySelect.appendChild(chooseOpt);
  Object.keys(countryStateData).sort().forEach(c=>{
    const o=document.createElement("option"); o.value=c; o.textContent=c; if(c===selectedCountry) o.selected=true; countrySelect.appendChild(o);
  });
  function updateStates(c){
    stateSelect.innerHTML="";
    const states = countryStateData[c]||[];
    if(states.length===0){const no=document.createElement("option"); no.value=""; no.textContent="-- No states --"; stateSelect.appendChild(no); return;}
    states.forEach(s=>{const so=document.createElement("option"); so.value=s; so.textContent=s; if(s===selectedState) so.selected=true; stateSelect.appendChild(so);});
  }
  countrySelect.addEventListener("change",function(){updateStates(this.value);});
  if(selectedCountry) updateStates(selectedCountry);
}

async function populateCountryAndState(countrySelectId,stateSelectId,selectedCountry="",selectedState=""){
  const data = await safeFetchJSON("/data/countries+states.json");
  if(!data) return;
  if(Array.isArray(data)){const map={};data.forEach(item=>{const name=item.country||item.name; map[name]=item.states||[];}); populateFromObject(map,countrySelectId,stateSelectId,selectedCountry,selectedState);}
  else if(typeof data==='object') populateFromObject(data,countrySelectId,stateSelectId,selectedCountry,selectedState);
}

document.addEventListener("DOMContentLoaded",function(){
  populateCountryAndState("country","state");
  document.querySelectorAll("[id^='country-']").forEach(countrySel=>{
    const id=countrySel.id.split("-")[1];
    const stateSel=document.getElementById("state-"+id);
    const preC=countrySel.getAttribute("data-selected")||"";
    const preS=stateSel.getAttribute("data-selected")||"";
    populateCountryAndState(countrySel.id,stateSel.id,preC,preS);
  });

  // View More toggle
  document.body.addEventListener("click", function(e){
    const btn = e.target.closest(".message .btn.btn-primary");
    if(!btn) return;
    e.preventDefault();
    const msg = btn.closest(".message");
    const vis = msg.querySelector(".visible-text");
    const hid = msg.querySelector(".hidden-text");
    const isHidden = window.getComputedStyle(hid).display==="none";
    if(isHidden){hid.style.display="block"; vis.style.display="none"; btn.textContent="View Less";}
    else{hid.style.display="none"; vis.style.display="inline-block"; btn.textContent="View More";}
  });
});
</script>

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