<?php
// admin_personalize.php
// Admin panel to manage personalization requests: update price, status, reply, upload PDF

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

// load DB config (should provide $DB_HOST, $DB_USER, $DB_PASS, $DB_NAME)
require_once __DIR__ . '/../config.php'; // adjust path if needed

// --- helpers ---
function e($v) { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
function flash_set($k, $v) { $_SESSION['admin_flash'][$k] = $v; }
function flash_get_all() { $out = $_SESSION['admin_flash'] ?? []; unset($_SESSION['admin_flash']); return $out; }

// --- connect ---
$conn = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if ($conn->connect_error) {
    http_response_code(500);
    echo "DB connect error: " . e($conn->connect_error);
    exit;
}
$conn->set_charset('utf8mb4');

// --- ensure tables exist ---
$conn->query("
CREATE TABLE IF NOT EXISTS personalization (
    id INT AUTO_INCREMENT PRIMARY KEY,
    `user` VARCHAR(255) NOT NULL,
    tracking_id VARCHAR(120),
    price DECIMAL(12,2) NOT NULL DEFAULT 0,
    status ENUM('pending','in_progress','ipe','successful','invalid') DEFAULT 'pending',
    admin_reply TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

$conn->query("
CREATE TABLE IF NOT EXISTS personalize_files (
    id INT AUTO_INCREMENT PRIMARY KEY,
    personalization_id INT NOT NULL,
    filename VARCHAR(255) NOT NULL,
    uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (personalization_id) REFERENCES personalization(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

$conn->query("
CREATE TABLE IF NOT EXISTS personalize_price (
    id INT AUTO_INCREMENT PRIMARY KEY,
    price DECIMAL(12,2) NOT NULL,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

// ensure there's at least one price row
$res = $conn->query("SELECT COUNT(*) AS c FROM personalize_price");
if ($res) {
    $row = $res->fetch_assoc();
    if (intval($row['c']) === 0) {
        $stmt = $conn->prepare("INSERT INTO personalize_price (price) VALUES (?)");
        $defaultPrice = 400.00;
        $stmt->bind_param("d", $defaultPrice);
        $stmt->execute();
        $stmt->close();
    }
    $res->free();
}

// --- POST handlers ---

// Update global price
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_price'])) {
    $newPrice = floatval($_POST['price'] ?? 0);
    if ($newPrice <= 0) {
        flash_set('error', 'Invalid price value.');
    } else {
        $stmt = $conn->prepare("INSERT INTO personalize_price (price) VALUES (?)");
        $stmt->bind_param("d", $newPrice);
        if ($stmt->execute()) flash_set('success', 'Price updated to ₦' . number_format($newPrice,2));
        else flash_set('error', 'Unable to update price: ' . $stmt->error);
        $stmt->close();
    }
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

// Update status & admin reply for a personalization
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_request'])) {
    $id = intval($_POST['id'] ?? 0);
    $status = $_POST['status'] ?? 'pending';
    $admin_reply = trim($_POST['admin_reply'] ?? '');

    if ($id <= 0) {
        flash_set('error', 'Invalid request id.');
    } else {
        $stmt = $conn->prepare("UPDATE personalization SET status = ?, admin_reply = ? WHERE id = ? LIMIT 1");
        $stmt->bind_param("ssi", $status, $admin_reply, $id);
        if ($stmt->execute()) flash_set('success', "Request #$id updated.");
        else flash_set('error', "Update failed: " . $stmt->error);
        $stmt->close();
    }

    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

// Upload PDF for a personalization
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload_pdf'])) {
    $id = intval($_POST['id'] ?? 0);
    if ($id <= 0) {
        flash_set('error', 'Invalid request id for upload.');
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    }

    if (!isset($_FILES['pdf_file']) || $_FILES['pdf_file']['error'] !== UPLOAD_ERR_OK) {
        flash_set('error', 'No file uploaded or upload error.');
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    }

    $file = $_FILES['pdf_file'];
    $allowedMime = ['application/pdf'];
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);

    // check mime and extension
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($mime, $allowedMime) || $ext !== 'pdf') {
        flash_set('error', 'Only PDF files are allowed.');
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    }

    // prepare upload folder
    $uploadDir = __DIR__ . '/uploads/personalize/';
    if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);

    $uniq = time() . '_' . bin2hex(random_bytes(6));
    $safeName = 'personalize_' . intval($id) . '_' . $uniq . '.pdf';
    $dest = $uploadDir . $safeName;

    if (!move_uploaded_file($file['tmp_name'], $dest)) {
        flash_set('error', 'Failed to move uploaded file.');
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    }

    // store file record
    $stmt = $conn->prepare("INSERT INTO personalize_files (personalization_id, filename) VALUES (?, ?)");
    $stmt->bind_param("is", $id, $safeName);
    if ($stmt->execute()) {
        // also optionally set status to successful if desired
        flash_set('success', 'PDF uploaded for request #' . $id);
    } else {
        flash_set('error', 'Failed to record file: ' . $stmt->error);
    }
    $stmt->close();

    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

// Handle downloads (admin)
if (isset($_GET['download']) && is_numeric($_GET['download'])) {
    $id = intval($_GET['download']);
    $stmt = $conn->prepare("SELECT filename FROM personalize_files WHERE personalization_id = ? ORDER BY id DESC LIMIT 1");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($row = $res->fetch_assoc()) {
        $filename = $row['filename'];
        $path = __DIR__ . '/uploads/personalize/' . $filename;
        if (is_file($path)) {
            header('Content-Type: application/pdf');
            header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
            header('Content-Length: ' . filesize($path));
            readfile($path);
            exit;
        } else {
            flash_set('error', 'File not found on server.');
        }
    } else {
        flash_set('error', 'No file associated with that request.');
    }
    $stmt->close();
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

// --- fetch current price ---
$price = 0.00;
if ($stmt = $conn->prepare("SELECT price FROM personalize_price ORDER BY id DESC LIMIT 1")) {
    $stmt->execute();
    $res = $stmt->get_result();
    if ($r = $res->fetch_assoc()) $price = (float)$r['price'];
    $stmt->close();
}

// --- fetch requests ---
$requests = [];
$q = $conn->query("SELECT id, `user`, tracking_id, price, status, admin_reply, created_at FROM personalization ORDER BY id DESC LIMIT 200");
if ($q) {
    while ($row = $q->fetch_assoc()) $requests[] = $row;
    $q->free();
}

$flash = flash_get_all();

// close connection later after output
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Admin — Personalize Manager</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<style>
:root{--bg:#071633;--card:rgba(255,255,255,0.04);--accent:#00bfff;--muted:rgba(255,255,255,0.8)}
*{box-sizing:border-box;margin:0;padding:0;font-family:Inter,Arial,sans-serif}
body{background:linear-gradient(135deg,#0a1e44,#0d47a1);color:#eaf2ff;min-height:100vh;padding:14px}
.container{max-width:1100px;margin:0 auto}
.header{display:flex;justify-content:space-between;align-items:center;gap:12px;margin-bottom:12px}
.card{background:var(--card);padding:14px;border-radius:12px;margin-bottom:12px;border:1px solid rgba(255,255,255,0.03)}
.h1{font-size:20px;font-weight:700;color:var(--accent)}
.form-row{display:flex;gap:10px;align-items:center;flex-wrap:wrap}
.input,textarea,select{background:rgba(0,0,0,0.12);border:1px solid rgba(255,255,255,0.05);color:#eaf2ff;padding:8px;border-radius:8px}
.small{font-size:13px;color:var(--muted)}
.button{background:linear-gradient(90deg,#0056b3,var(--accent));border:0;color:#012;padding:9px 12px;border-radius:8px;cursor:pointer}
.table{width:100%;border-collapse:collapse;margin-top:12px}
.table th{background:rgba(255,255,255,0.03);padding:10px;text-align:left;color:#eaf2ff;position:sticky;top:0}
.table td{padding:8px;border-top:1px solid rgba(255,255,255,0.03);vertical-align:top}
.status-badge{padding:6px 8px;border-radius:8px;color:#012;font-weight:700;display:inline-block}
.bad-gray{background:#9aa7b8}
.bad-orange{background:#f59e0b}
.bad-blue{background:#3b82f6}
.bad-green{background:#16a34a}
.bad-red{background:#ef4444}
.reply-box{white-space:pre-wrap;background:rgba(0,0,0,0.12);padding:8px;border-radius:6px}
.actions{display:flex;gap:8px;flex-direction:column}
.file-input{padding:4px}
@media(max-width:900px){
  .form-row{flex-direction:column}
  .header{flex-direction:column;align-items:flex-start;gap:8px}
  .actions{flex-direction:column}
  .table th:nth-child(1), .table td:nth-child(1) {display:none}
}
</style>
</head>
<body>
<div class="container">
  <div class="header">
    <div>
      <div class="h1">Admin — Personalization Manager</div>
      <div class="small">Signed in as: <strong><?= e($_SESSION['admin']) ?></strong></div>
    </div>

    <div style="text-align:right">
      <form method="post" style="display:flex;gap:8px;align-items:center">
        <label class="small" for="price">Price: ₦</label>
        <input id="price" name="price" type="number" step="0.01" value="<?= number_format($price,2,'.','') ?>" class="input" style="width:110px">
        <button name="update_price" class="button">Update Price</button>
      </form>
    </div>
  </div>

  <?php if(!empty($flash['success'])): ?>
    <div class="card" style="border-left:4px solid #16a34a; color:#bbf7d0"><?= e($flash['success']) ?></div>
  <?php endif;?>
  <?php if(!empty($flash['error'])): ?>
    <div class="card" style="border-left:4px solid #ef4444; color:#ffc2c2"><?= e($flash['error']) ?></div>
  <?php endif;?>

  <div class="card">
    <h3 style="margin-bottom:8px">Requests (latest first)</h3>
    <?php if(empty($requests)): ?>
      <div class="small">No personalization requests yet.</div>
    <?php else: ?>
      <div style="overflow:auto">
      <table class="table" role="table">
        <thead>
          <tr>
            <th>ID</th>
            <th>User</th>
            <th>Tracking ID</th>
            <th>Price</th>
            <th>Status</th>
            <th>Admin Reply</th>
            <th>Submitted At</th>
            <th>File</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach($requests as $r): 
            $st = strtolower($r['status']);
            $badgeClass = 'bad-gray';
            if ($st === 'successful') $badgeClass = 'bad-green';
            elseif ($st === 'ipe') $badgeClass = 'bad-blue';
            elseif ($st === 'in progress') $badgeClass = 'bad-orange';
            elseif ($st === 'invalid') $badgeClass = 'bad-red';
            // check file
            $stmtf = $conn->prepare("SELECT filename FROM personalize_files WHERE personalization_id = ? ORDER BY id DESC LIMIT 1");
            $stmtf->bind_param("i", $r['id']);
            $stmtf->execute();
            $rf = $stmtf->get_result()->fetch_assoc();
            $stmtf->close();
            $hasFile = $rf ? true : false;
            $fileName = $rf['filename'] ?? '';
          ?>
          <tr>
            <td class="small"><?= e($r['id']) ?></td>
            <td class="small"><?= e($r['user']) ?></td>
            <td class="small"><?= e($r['tracking_id']) ?></td>
            <td class="small">₦<?= number_format((float)$r['price'],2) ?></td>
            <td><span class="status-badge <?= $badgeClass ?>"><?= strtoupper(e($r['status'])) ?></span></td>
            <td style="max-width:220px"><div class="reply-box"><?= e($r['admin_reply']) ?></div></td>
            <td class="small"><?= e($r['created_at']) ?></td>
            <td class="small">
              <?php if($hasFile): ?>
                <a class="button" href="<?= $_SERVER['PHP_SELF'] . '?download=' . intval($r['id']) ?>">Download</a>
              <?php else: ?>
                <span class="small" style="color:#9aa7b8">No file</span>
              <?php endif; ?>
            </td>
            <td>
              <div class="actions">
                <!-- update form -->
                <form method="post" style="display:flex;flex-direction:column;gap:6px">
                  <input type="hidden" name="id" value="<?= e($r['id']) ?>">
                  <select name="status" class="input" style="max-width:170px">
                    <option value="pending" <?= $r['status']=='pending' ? 'selected' : '' ?>>Pending</option>
                    <option value="in progress" <?= $r['status']=='in progress' ? 'selected' : '' ?>>in progress</option>
                    <option value="ipe" <?= $r['status']=='ipe' ? 'selected' : '' ?>>IPE</option>
                    <option value="successful" <?= $r['status']=='successful' ? 'selected' : '' ?>>Successful</option>
                    <option value="invalid" <?= $r['status']=='invalid' ? 'selected' : '' ?>>Invalid</option>
                  </select>
                  <textarea name="admin_reply" placeholder="Reply..." class="input" style="height:70px"><?= e($r['admin_reply']) ?></textarea>
                  <button name="update_request" class="button" type="submit">Update</button>
                </form>

                <!-- upload PDF -->
                <form method="post" enctype="multipart/form-data" style="margin-top:6px;display:flex;flex-direction:column;gap:6px">
                  <input type="hidden" name="id" value="<?= e($r['id']) ?>">
                  <input type="file" name="pdf_file" accept="application/pdf" class="file-input">
                  <button name="upload_pdf" class="button" type="submit">Upload PDF</button>
                </form>
              </div>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
      </div>
    <?php endif; ?>
  </div>

</div>

</body>
</html>
<?php
$conn->close();