<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// admin_product_approval.php
session_start();
require_once __DIR__ . '/../config.php';

// AUTH: only admin allowed
if (!isset($_SESSION['user_id']) || ($_SESSION['role'] ?? '') !== 'admin') {
    header('Location: ../login.php');
    exit;
}

$admin_id = (int)$_SESSION['user_id'];

// helper
function e($v){ return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }

// CSRF token
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(16));
}
$csrf = $_SESSION['csrf_token'];

$errors = [];
$messages = [];

/* ---------- Handle POST actions: approve / reject / bulk approve ---------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
        $errors[] = 'Invalid CSRF token.';
    } else {

        /* APPROVE */
        if (isset($_POST['approve'])) {

            $id = (int)($_POST['id'] ?? 0);

            $stmt = $conn->prepare("SELECT * FROM admin_product_approval WHERE id=?");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $row = $stmt->get_result()->fetch_assoc();
            $stmt->close();

            if (!$row) {
                $errors[] = "Request not found.";
            } elseif ($row['status'] !== 'pending') {
                $errors[] = "Already processed.";
            } else {

                $product_id = 0;

                /* ADD */
              if ($row['type'] === 'add' || $row['type'] === 'edit') {

    $data = json_decode($row['variation'], true) ?: [];
    $product_id = (int)($row['product_id'] ?? 0);

    /* EDIT EXISTING PRODUCT */
    if ($row['type'] === 'edit' && $product_id > 0) {

        $stmt2 = $conn->prepare("
            UPDATE products SET
                product_name=?,
                generic_name=?,
                brand_name=?,
                standards=?,
                strength=?,
                volume=?,
                dosage_form=?,
                shelf_life=?,
                indication=?,
                primary_packing=?,
                manufactured_by=?,
                marketed_by=?,
                distributed_by=?,
                country_id=?,
                hsn_no=?,           -- ✅ ADD THIS
                dossier_type=?
            WHERE id=?
        ");

            $stmt2->bind_param(
                "ssssssssssssssisi",
            $data['product_name'],
            $data['generic_name'],
            $data['brand_name'],
            $data['standards'],
            $data['strength'],
            $data['volume'],
            $data['dosage_form'],
            $data['shelf_life'],
            $data['indication'],
            $data['packing'],
            $data['manufactured_by'],
            $data['marketed_by'],
            $data['distributed_by'],
            $data['country_id'],
            $data['hsn_no'],     // ✅ ADD THIS
            $data['dossier_type'],
            $product_id
        );

        if ($stmt2->execute()) {
            $messages[] = "Product updated successfully.";
        } else {
            $errors[] = $stmt2->error;
        }

    } else {

        /* ADD NEW PRODUCT */
        $stmt2 = $conn->prepare("
            INSERT INTO products (
                product_name,
                generic_name,
                brand_name,
                standards,
                strength,
                volume,
                dosage_form,
                shelf_life,
                indication,
                primary_packing,
                manufactured_by,
                marketed_by,
                distributed_by,
                country_id,
                dossier_type,
                status,
                created_at
            ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'approved',NOW())
        ");

        $stmt2->bind_param(
            "sssssssssssssis",
            $data['product_name'],
            $data['generic_name'],
            $data['brand_name'],
            $data['standards'],
            $data['strength'],
            $data['volume'],
            $data['dosage_form'],
            $data['shelf_life'],
            $data['indication'],
            $data['packing'],
            $data['manufactured_by'],
            $data['marketed_by'],
            $data['distributed_by'],
            $data['country_id'],
            $data['dossier_type']
        );

        if ($stmt2->execute()) {
            $product_id = $stmt2->insert_id;
            $messages[] = "Product added successfully.";
        } else {
            $errors[] = $stmt2->error;
        }
    }

    $stmt2->close();
}

                /* VARIATION */
                elseif ($row['type'] === 'variation') {

                    $data = json_decode($row['variation'], true) ?: [];
                    $product_id = (int)($row['product_id'] ?? 0);

                    if ($product_id <= 0) {
                        $stmtP = $conn->prepare("
                            INSERT INTO products (product_name, status, created_at)
                            VALUES (?, 'approved', NOW())
                        ");
                        $stmtP->bind_param("s", $row['product_name']);
                        $stmtP->execute();
                        $product_id = $stmtP->insert_id;
                        $stmtP->close();
                    }

                    $stmtNo = $conn->prepare("
                        SELECT COALESCE(MAX(variation_no),0)+1 AS next_no
                        FROM product_variations
                        WHERE product_id=?
                    ");
                    $stmtNo->bind_param("i", $product_id);
                    $stmtNo->execute();
                    $variation_no = $stmtNo->get_result()->fetch_assoc()['next_no'] ?? 1;
                    $stmtNo->close();

                    $variation_type = $data['variation_type'] ?? 'Product Update';
                    $variation_description = $data['variation_description'] ?? 'Approved variation';
                    $submission_date = $data['submission_date'] ?? date('Y-m-d');
                    $approval_date = date('Y-m-d');
                    $comments = $data['comments'] ?? null;
                    $document_file = $data['document_file'] ?? null;

                    $stmt2 = $conn->prepare("
                        INSERT INTO product_variations
                        (product_id, variation_no, variation_type, variation_description, submission_date, approval_date, comments, document_file, status, approved_by, approved_at)
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'approved', ?, NOW())
                    ");

                    $stmt2->bind_param(
                        "iissssssi",
                        $product_id,
                        $variation_no,
                        $variation_type,
                        $variation_description,
                        $submission_date,
                        $approval_date,
                        $comments,
                        $document_file,
                        $admin_id
                    );

                    if ($stmt2->execute()) {
                        $messages[] = "Variation approved & saved.";
                    } else {
                        $errors[] = "Insert error: " . $stmt2->error;
                    }

                    $stmt2->close();
                }

               $stmt3 = $conn->prepare("
    UPDATE admin_product_approval
    SET status='approved',
        product_id=?
    WHERE id=?
");
$stmt3->bind_param("ii", $product_id, $id);
                $stmt3->execute();
                $stmt3->close();
            }
        }

        /* REJECT */
        if (isset($_POST['reject'])) {
            $id = (int)($_POST['id'] ?? 0);

            if ($id <= 0) {
                $errors[] = 'Invalid product id.';
            } else {
                $stmt = $conn->prepare("
                    UPDATE admin_product_approval
                    SET status='rejected'
                    WHERE id=? AND status='pending'
                ");
                $stmt->bind_param("i", $id);

                if ($stmt->execute()) {
                    if ($stmt->affected_rows > 0) {
                        $messages[] = "Product #$id rejected.";
                    } else {
                        $errors[] = "Product #$id was not pending or does not exist.";
                    }
                } else {
                    $errors[] = 'DB error: ' . $stmt->error;
                }

                $stmt->close();
            }
        }
    }
}
/* ---------- Fetch pending products (or allow admin to view all via GET param) ---------- */
$show = $_GET['show'] ?? 'pending';
$allowed_show = in_array($show, ['pending', 'all']) ? $show : 'pending';

$sql = "SELECT * FROM admin_product_approval";

if ($allowed_show === 'pending') {
    $sql .= " WHERE status='pending'";
}

$sql .= " ORDER BY created_at DESC";

$res = $conn->query($sql);
$products = [];
if ($res) {
    $products = $res->fetch_all(MYSQLI_ASSOC);
    $res->free();
} else {
    $errors[] = 'DB error: ' . $conn->error;
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Admin Product Approval</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
:root{
    --bg:#f4f6fb;
    --card:#ffffff;
    --text:#000;
    --muted:#555;
    --border:#e5e7eb;
    --shadow:0 12px 30px rgba(0,0,0,0.08);
    --radius:18px;
    --sidebar:260px;
}

*{
    box-sizing:border-box;
}

body{
    margin:0;
    font-family: Arial, Helvetica, sans-serif;
    background:var(--bg);
    color:var(--text);
}

.container{
    margin-left: var(--sidebar);
    padding: 58px 18px 18px;
    min-height: 100vh;
}

.page-header{
    color:#000;
    padding:14px 16px;
    border-radius:var(--radius);
    margin-bottom:0px;
}

.page-header h1{
    margin:0;
    font-size:24px;
    line-height:1.2;
}

.page-header p{
    margin:6px 0 0;
    font-size:14px;
    opacity:0.82;
}

.card{
    background:var(--card);
    border-radius:var(--radius);
    box-shadow:var(--shadow);
    padding:12px;
    border:1px solid var(--border);
}

.top-actions{
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:12px;
    flex-wrap:wrap;
    margin-bottom:15px;
}

.small{
    color:var(--muted);
    font-size:14px;
}

.btn{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:8px;
    padding:7px 12px;
    font-size:13px;
    border-radius:10px;
    border:none;
    font-weight:600;
    cursor:pointer;
    background:#111;
    color:#fff;
    transition:0.2s;
    text-decoration:none !important;
    white-space:nowrap;
}

.btn:hover{
    transform:translateY(-1px);
    box-shadow:0 8px 18px rgba(0,0,0,0.15);
}

.btn.ghost{
    background:#fff;
    color:#000;
    border:1px solid var(--border);
}

.notice{
    padding:12px 14px;
    border-radius:10px;
    margin-bottom:12px;
    font-size:14px;
}

.notice.success{
    background:#ecfdf3;
    color:#027a48;
}

.notice.error{
    background:#fef3f2;
    color:#b42318;
}

.table-wrap{
    overflow-x:auto;
}

.table{
    width:100%;
    border-collapse:collapse;
    margin-top:10px;
    min-width:1100px;
}

.table th{
    background:#000;
    color:#fff;
    font-size:13px;
    text-transform:uppercase;
    letter-spacing:.3px;
    padding:10px 10px;
    border-bottom:1px solid var(--border);
    text-align:left;
    white-space:nowrap;
}

.table td{
    padding:10px 10px;
    border-bottom:1px solid #f1f1f1;
    font-size:14px;
    color:#000;
    vertical-align:middle;
}

.table tr:hover{
    background:#fafafa;
}

.status{
    display:inline-flex;
    align-items:center;
    padding:5px 10px;
    border-radius:999px;
    font-size:12px;
    font-weight:600;
}

.status.pending{
    background:#fff3cd;
    color:#856404;
}

.status.approved{
    background:#d1fae5;
    color:#065f46;
}

.status.rejected{
    background:#fee2e2;
    color:#991b1b;
}

.actions{
    display:flex;
    gap:8px;
    flex-wrap:wrap;
    align-items:center;
}

.row-form{
    display:flex;
    gap:8px;
    flex-wrap:wrap;
    align-items:center;
    margin:0;
}

.bulk-bar{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:12px;
    flex-wrap:wrap;
    margin-bottom:14px;
    padding:12px 14px;
    border:1px solid var(--border);
    border-radius:14px;
    background:#fafafa;
}

.bulk-left{
    display:flex;
    align-items:center;
    gap:10px;
    flex-wrap:wrap;
}

.bulk-right{
    display:flex;
    align-items:center;
    gap:8px;
    flex-wrap:wrap;
}

.bulk-btn{
    background:#111;
    color:#fff;
    border:none;
    border-radius:10px;
    padding:9px 14px;
    font-weight:700;
    cursor:pointer;
}

.bulk-btn:hover{
    opacity:.92;
}

@media(max-width:900px){
    .container{
        margin-left:0;
        padding:16px;
    }
}

@media(max-width:640px){
    .page-header{
        padding:18px;
    }

    .page-header h1{
        font-size:22px;
    }

    .card{
        padding:14px;
    }
}
/* ================= MOBILE RESPONSIVE ================= */
@media (max-width: 768px) {

    /* HEADER FIX */
    body {
        padding-top: 65px;
    }

    /* CONTAINER FULL WIDTH */
    .container {
        margin-left: 0 !important;
        padding: 12px;
    }

    /* PAGE HEADER */
    .page-header {
        padding: 12px;
    }

    .page-header h1 {
        font-size: 18px;
    }

    .page-header p {
        font-size: 12px;
    }

    /* CARD */
    .card {
        padding: 10px;
        border-radius: 12px;
    }

    /* TOP BUTTONS */
    .top-actions {
        flex-direction: column;
        align-items: flex-start;
        gap: 8px;
    }

    .btn {
        font-size: 12px;
        padding: 6px 10px;
    }

    /* TABLE SCROLL FIX */
    .table-wrap {
        overflow-x: auto;
    }

    .table {
        min-width: 700px; /* important */
    }

    /* TABLE TEXT */
    .table th,
    .table td {
        font-size: 12px;
        padding: 8px;
        white-space: nowrap;
    }

    /* STATUS BADGE */
    .status {
        font-size: 11px;
        padding: 4px 8px;
    }

    /* ACTION BUTTONS */
    .actions {
        flex-direction: column;
        align-items: flex-start;
        gap: 6px;
    }

    .row-form {
        flex-direction: column;
        align-items: flex-start;
    }

    /* NOTICE */
    .notice {
        font-size: 12px;
        padding: 10px;
    }
}
</style>
</head>
<body>

<?php include "adminsidebar.php"; ?>
<?php include "../header.php"; ?>

<div class="container">
    <div class="page-header">
        <h1><i class="fa-solid fa-clipboard-check"></i> Product Approvals</h1>
        <p>Approve or reject submitted products.</p>
    </div>

    <?php foreach ($messages as $m): ?>
        <div class="notice success"><?php echo e($m); ?></div>
    <?php endforeach; ?>

    <?php foreach ($errors as $er): ?>
        <div class="notice error"><?php echo e($er); ?></div>
    <?php endforeach; ?>

    <div class="card">
        <div class="top-actions">
            <div class="small">Showing: <strong><?php echo e(ucfirst($allowed_show)); ?></strong></div>
            <div style="display:flex;gap:8px;flex-wrap:wrap;">
                <a class="btn <?php echo $allowed_show === 'pending' ? '' : 'ghost'; ?>" href="?show=pending">Pending</a>
                <a class="btn <?php echo $allowed_show === 'all' ? '' : 'ghost'; ?>" href="?show=all">All</a>
            </div>
        </div>

     

          

            <div class="table-wrap">
                <table class="table">
                    <thead>
                        <tr>
                            <th style="width:48px;">
                            </th>
                            <th style="width:80px;">No.</th>
                            <th>Product</th>
                            <th>Brand</th>
                            <th>Dossier</th>
                            <th style="width:140px;">Submitted On</th>
                            <th>Country</th>
                            <th style="width:120px;">Status</th>
                            <?php if ($allowed_show === 'pending'): ?>
                            <th style="width:260px;">Actions</th>
                        <?php endif; ?>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($products)): ?>
                            <tr>
                                <td colspan="<?php echo $allowed_show === 'pending' ? 9 : 8; ?>" class="small">
                            No products found.
                        </td>
                            </tr>
                        <?php else: ?>
                            <?php $i = 1; ?>
                                <?php foreach ($products as $p): ?>
                                <tr>
                                    <td>
                                       
                                    </td>
                                    <td><?php echo $i++; ?></td>
<td><?php echo e($p['product_name'] ?? '-'); ?></td>
<td><?php echo e($p['type']); ?></td>
<td> <?php $variation = json_decode($p['variation'], true); echo e($variation['dossier_type'] ?? '-'); ?> </td>
                                    <td class="small">     <?php echo !empty($p['submitted_on']) ? date('Y-m-d', strtotime($p['submitted_on'])) : '—'; ?> </td>
                                    <td class="small"> <?php $variation = json_decode($p['variation'], true); echo e($variation['country_name'] ?? '-'); ?> </td>
                                    <td>
                                        <span class="status <?php echo strtolower($p['status']); ?>">
                                            <?php echo ucfirst(e($p['status'] ?? 'pending')); ?>
                                        </span>
                                    </td>
                                    <?php if ($allowed_show === 'pending'): ?>
                                    <td>
                                        <div class="actions">

                                            <?php if (($p['status'] ?? 'pending') === 'pending'): ?>
                                                <form method="post" class="row-form">
                                                    <input type="hidden" name="csrf_token" value="<?php echo e($csrf); ?>">
                                                    <input type="hidden" name="id" value="<?php echo e($p['id']); ?>">

                                                    <button class="btn" type="submit" name="approve">Approve</button>
                                                    <button class="btn ghost" type="submit" name="reject">Reject</button>
                                                </form>
                                            <?php else: ?>
                                                <span style="color:gray; font-size:13px;">No action</span>
                                            <?php endif; ?>

                                            <a class="btn ghost" href="view_product.php?id=<?php echo e($p['product_id']); ?>">View</a>

                                        </div>
                                    </td>
                                    <?php endif; ?>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        
    </div>
</div>

<script>
(function () {
    const checkAll = document.getElementById('checkAll');
    const checkAllHeader = document.getElementById('checkAllHeader');
    const boxes = () => document.querySelectorAll('input[name="ids[]"]');

    function setAll(checked) {
        boxes().forEach(cb => cb.checked = checked);
        if (checkAll) checkAll.checked = checked;
        if (checkAllHeader) checkAllHeader.checked = checked;
    }

    checkAll?.addEventListener('change', function () {
        setAll(this.checked);
    });

    checkAllHeader?.addEventListener('change', function () {
        setAll(this.checked);
    });
})();
</script>

</body>
</html>