<?php
session_start();
require_once '../config.php';

error_reporting(E_ALL);
ini_set('display_errors', 1);

if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit;
}

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

$message = '';
$messageType = 'error';

/* =========================
   FETCH USER COUNTRY
========================= */

$userCountry = '';

$stmt = $conn->prepare("
    SELECT country
    FROM users
    WHERE id = ?
");

$stmt->bind_param("i", $userId);
$stmt->execute();

$res = $stmt->get_result();

if($row = $res->fetch_assoc()){
    $userCountry = trim($row['country']);
}

$stmt->close();

/* =========================
   FIND COUNTRY ID
========================= */

$countryId = 0;

if($userCountry != ''){

    $stmt = $conn->prepare("
        SELECT id
        FROM countries
        WHERE country_name = ?
    ");

    $stmt->bind_param("s", $userCountry);
    $stmt->execute();

    $res = $stmt->get_result();

    if($row = $res->fetch_assoc()){
        $countryId = (int)$row['id'];
    }

    $stmt->close();
}

/* =========================
   FETCH PRODUCTS
========================= */

$products = [];

if($countryId > 0){

    $stmt = $conn->prepare("
        SELECT id, product_name
        FROM products
        WHERE country_id = ?
        ORDER BY product_name ASC
    ");

    $stmt->bind_param("i", $countryId);
    $stmt->execute();

    $res = $stmt->get_result();

    if($res){

        while($row = $res->fetch_assoc()){

            $products[] = $row;
        }
    }

    $stmt->close();
}

/* =========================
   SAVE ORDER
========================= */

if(isset($_POST['submit_order'])){

    $product_id = (int)($_POST['product_id'] ?? 0);
    $qty        = (int)($_POST['qty'] ?? 0);
    $notes      = trim($_POST['notes'] ?? '');

    if($product_id <= 0 || $qty <= 0){

        $message = "Please select product and quantity.";
        $messageType = "error";

    }else{

        $stmt = $conn->prepare("
            INSERT INTO orders
            (
                mr_id,
                product_id,
                qty,
                notes,
                status,
                created_at
            )
            VALUES
            (
                ?, ?, ?, ?, 'Pending', NOW()
            )
        ");

        $stmt->bind_param(
            "iiis",
            $userId,
            $product_id,
            $qty,
            $notes
        );

        if($stmt->execute()){

            $message = "Order request submitted successfully.";
            $messageType = "success";

        }else{

            $message = "Failed to submit request.";
            $messageType = "error";
        }

        $stmt->close();
    }
}

/* =========================
   RECENT ORDERS
========================= */

$recentOrders = [];

$stmt = $conn->prepare("
    SELECT 
        o.id,
        o.qty,
        o.notes,
        o.status,
        o.created_at,
        p.product_name

    FROM orders o

    LEFT JOIN products p
    ON p.id = o.product_id

    WHERE o.mr_id = ?

    ORDER BY o.id DESC

    LIMIT 10
");

$stmt->bind_param("i", $userId);
$stmt->execute();

$res = $stmt->get_result();

if($res){
    $recentOrders = $res->fetch_all(MYSQLI_ASSOC);
}

$stmt->close();

/* =========================
   FUNCTIONS
========================= */

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

function badge($status){

    $status = strtolower(trim($status));

    if($status == 'approved'){
        return 'approved';
    }

    if($status == 'rejected'){
        return 'rejected';
    }

    return 'pending';
}
?>

<!doctype html>
<html lang="en">

<head>

<meta charset="utf-8">

<meta name="viewport"
content="width=device-width, initial-scale=1">

<title>New Order</title>

<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap"
rel="stylesheet">

<style>

:root{

    --sidebar-width:260px;

    --bg:#f1f5f9;
    --card:#ffffff;

    --text:#0f172a;
    --muted:#64748b;

    --primary:#334155;
    --primary-light:#475569;

    --success:#16a34a;
    --danger:#dc2626;

    --border:#dbe4ee;

    --shadow:
        0 4px 18px rgba(15,23,42,.05);

    --radius:18px;
}

*{
    box-sizing:border-box;
}

body{
    margin:0;
    font-family:'Inter',sans-serif;
    background:#f1f5f9;
    color:var(--text);
}

/* PAGE */

.page{
    margin-left:var(--sidebar-width);
    padding:25px;
    min-height:100vh;
}

/* HERO */

.hero{
    background:#fff;
    border:1px solid var(--border);
    border-radius:20px;
    padding:18px 22px;
    margin-bottom:14px;
    box-shadow:var(--shadow);
}

.hero h1{
    margin:0;
    font-size:20px;
    font-weight:800;
    display:flex;
    align-items:center;
    gap:10px;
    color:#0f172a;
}

.hero h1 i{
    color:#334155;
}

.hero p{
    margin:6px 0 0;
    color:#64748b;
    font-size:13px;
}

/* GRID */

.grid{
    display:grid;
    grid-template-columns:1fr 1fr;
    gap:14px;
}

/* CARD */

.card{
    background:#fff;
    border-radius:20px;
    border:1px solid var(--border);
    overflow:hidden;
    box-shadow:var(--shadow);
}

.card-head{
    padding:14px 18px;
    border-bottom:1px solid #eef2f7;
    background:#fff;
}

.card-head h2{
    margin:0;
    font-size:15px;
    font-weight:700;
    color:#0f172a;
}

.card-body{
    padding:18px;
}

/* FORM */

.field{
    margin-bottom:16px;
}

label{
    display:block;
    margin-bottom:7px;
    font-size:12px;
    font-weight:700;
    color:#334155;
}

.input{
    width:100%;
    height:46px;
    padding:0 14px;
    border-radius:14px;
    border:1px solid #dbe4ee;
    background:#fff;
    outline:none;
    font-size:13px;
    transition:.2s;
}

.input:focus{
    border-color:#334155;
    box-shadow:0 0 0 4px rgba(51,65,85,.10);
}

textarea.input{
    height:95px;
    padding-top:12px;
    resize:none;
}

/* BUTTON */

.btn{
    width:100%;
    height:48px;
    border:none;
    border-radius:14px;
    background:#334155;
    color:#fff;
    font-size:14px;
    font-weight:700;
    cursor:pointer;
    display:flex;
    align-items:center;
    justify-content:center;
    gap:8px;
    transition:.18s ease;
}

.btn:hover{
    background:#1e293b;
}

/* ALERT */

.alert{
    margin-bottom:14px;
    padding:12px 14px;
    border-radius:14px;
    font-size:13px;
    font-weight:600;
}

.alert.success{
    background:#ecfdf5;
    color:#166534;
    border:1px solid #bbf7d0;
}

.alert.error{
    background:#fef2f2;
    color:#991b1b;
    border:1px solid #fecaca;
}

/* TABLE */

.table-wrap{
    overflow:auto;
    cursor:grab;
    user-select:none;
    scroll-behavior:smooth;
}

.table-wrap.active{
    cursor:grabbing;
}

table{
    width:100%;
    border-collapse:collapse;
    min-width:520px;
}

thead{
    background:#334155;
}

th{
    padding:13px 14px;
    text-align:left;
    color:#fff;
    font-size:12px;
    font-weight:700;
    white-space:nowrap;
}

td{
    padding:13px 14px;
    border-bottom:1px solid #eef2f7;
    font-size:13px;
    color:#1e293b;
    background:#fff;
    white-space:nowrap;
}

tbody tr:hover td{
    background:#f8fbff;
}

/* BADGES */

.badge{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    min-width:76px;
    padding:6px 10px;
    border-radius:999px;
    font-size:10px;
    font-weight:700;
}

.pending{
    background:#fef3c7;
    color:#92400e;
}

.approved{
    background:#dcfce7;
    color:#166534;
}

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

/* CUSTOM DROPDOWN */

.custom-select{
    position:relative;
    width:100%;
}

.search-input{
    width:100%;
    height:46px;
    padding:0 14px;
    border-radius:14px;
    border:1px solid #dbe4ee;
    background:#fff;
    outline:none;
    font-size:13px;
    transition:.2s;
}

.search-input:focus{
    border-color:#334155;
    box-shadow:0 0 0 4px rgba(51,65,85,.10);
}

.select-dropdown{
    position:absolute;
    top:52px;
    left:0;
    width:100%;
    background:#fff;
    border:1px solid #dbe4ee;
    border-radius:14px;
    box-shadow:0 10px 25px rgba(0,0,0,.08);
    max-height:220px;
    overflow-y:auto;
    z-index:9999;
    display:none;
}

.select-item{
    padding:11px 14px;
    font-size:13px;
    cursor:pointer;
    border-bottom:1px solid #f1f5f9;
    background:#fff;
}

.select-item:last-child{
    border-bottom:none;
}

.select-item:hover{
    background:#f8fafc;
    color:#334155;
}

/* SCROLLBAR */

.table-wrap::-webkit-scrollbar,
.select-dropdown::-webkit-scrollbar{
    width:7px;
    height:7px;
}

.table-wrap::-webkit-scrollbar-thumb,
.select-dropdown::-webkit-scrollbar-thumb{
    background:#cbd5e1;
    border-radius:20px;
}

/* MOBILE */

@media(max-width:992px){

    .page{
        margin-left:0;
        padding:80px 12px 12px;
    }

    .grid{
        grid-template-columns:1fr;
    }
}

@media(max-width:768px){

    .hero{
        padding:16px;
    }

    .hero h1{
        font-size:18px;
    }

    .hero p{
        font-size:12px;
    }

    .card-body{
        padding:14px;
    }

    th{
        font-size:11px;
        padding:12px;
    }

    td{
        font-size:12px;
        padding:12px;
    }

    .badge{
        min-width:70px;
    }
}

</style>
</head>

<body>

<?php include 'salesexecutivesidebar.php'; ?>
<?php include '../header.php'; ?>

<div class="page">

    <!-- HERO -->

    <div class="hero">

        <h1>
            <i class="fa-solid fa-cart-shopping"></i>
            New Order Request
        </h1>

        <p>
            Only same-country products are visible.
        </p>

    </div>

    <!-- ALERT -->

    <?php if($message != ''): ?>

        <div class="alert <?php echo $messageType; ?>">

            <?php echo e($message); ?>

        </div>

    <?php endif; ?>

    <div class="grid">

        <!-- FORM -->

        <div class="card">

            <div class="card-head">

                <h2>Order Form</h2>

            </div>

            <div class="card-body">

                <form method="post">

                    <!-- PRODUCT -->

                    <div class="field">

                        <label>Product Name</label>

                        <div class="custom-select">

                            <input
                                type="text"
                                id="productSearch"
                                class="search-input"
                                placeholder="Search Product..."
                                autocomplete="off"
                            >

                            <div class="select-dropdown" id="productDropdown">

                                <?php foreach($products as $p): ?>

                                    <div
                                        class="select-item"
                                        data-value="<?php echo (int)$p['id']; ?>"
                                    >

                                        <?php echo e($p['product_name']); ?>

                                    </div>

                                <?php endforeach; ?>

                            </div>

                            <input
                                type="hidden"
                                name="product_id"
                                id="selectedProduct"
                                required
                            >

                        </div>

                    </div>

                    <!-- QTY -->

                    <div class="field">

                        <label>Quantity</label>

                        <input
                            type="number"
                            name="qty"
                            class="input"
                            placeholder="Enter quantity"
                            min="1"
                            required
                        >

                    </div>

                    <!-- NOTES -->

                    <div class="field">

                        <label>Notes</label>

                        <textarea
                            name="notes"
                            class="input"
                            placeholder="Example: urgent, next month"
                        ></textarea>

                    </div>

                    <!-- BUTTON -->

                    <button
                        type="submit"
                        name="submit_order"
                        class="btn"
                    >

                        <i class="fa-solid fa-paper-plane"></i>

                        Send Request

                    </button>

                </form>

            </div>

        </div>

        <!-- RECENT ORDERS -->

        <div class="card">

            <div class="card-head">

                <h2>Recent Requests</h2>

            </div>

            <div class="table-wrap">

                <table>

                    <thead>

                        <tr>

                            <th>ID</th>
                            <th>Product</th>
                            <th>Qty</th>
                            <th>Notes</th>
                            <th>Status</th>

                        </tr>

                    </thead>

                    <tbody>

                    <?php if(!empty($recentOrders)): ?>

                        <?php foreach($recentOrders as $row): ?>

                            <tr>

                                <td>
                                    <?php echo (int)$row['id']; ?>
                                </td>

                                <td>
                                    <?php echo e($row['product_name']); ?>
                                </td>

                                <td>
                                    <?php echo (int)$row['qty']; ?>
                                </td>

                                <td>
                                    <?php echo e($row['notes']); ?>
                                </td>

                                <td>

                                    <span class="badge <?php echo badge($row['status']); ?>">

                                        <?php echo e($row['status']); ?>

                                    </span>

                                </td>

                            </tr>

                        <?php endforeach; ?>

                    <?php else: ?>

                        <tr>

                            <td colspan="5">

                                No requests found.

                            </td>

                        </tr>

                    <?php endif; ?>

                    </tbody>

                </table>

            </div>

        </div>

    </div>

</div>

<!-- CUSTOM DROPDOWN -->

<script>

const searchInput = document.getElementById('productSearch');

const dropdown = document.getElementById('productDropdown');

const hiddenInput = document.getElementById('selectedProduct');

const items = document.querySelectorAll('.select-item');

/* OPEN */

searchInput.addEventListener('focus', () => {

    dropdown.style.display = 'block';
});

/* SEARCH */

searchInput.addEventListener('keyup', () => {

    let value = searchInput.value.toLowerCase();

    items.forEach(item => {

        let text = item.innerText.toLowerCase();

        item.style.display = text.includes(value)
            ? 'block'
            : 'none';
    });

    dropdown.style.display = 'block';
});

/* SELECT */

items.forEach(item => {

    item.addEventListener('click', () => {

        searchInput.value = item.innerText;

        hiddenInput.value = item.dataset.value;

        dropdown.style.display = 'none';
    });
});

/* OUTSIDE CLICK */

document.addEventListener('click', (e) => {

    if(!e.target.closest('.custom-select')){

        dropdown.style.display = 'none';
    }
});

/* DRAG TABLE */

const slider = document.querySelector('.table-wrap');

let isDown = false;
let startX;
let scrollLeft;

slider.addEventListener('mousedown', (e) => {

    isDown = true;

    slider.classList.add('active');

    startX = e.pageX - slider.offsetLeft;

    scrollLeft = slider.scrollLeft;
});

slider.addEventListener('mouseleave', () => {

    isDown = false;

    slider.classList.remove('active');
});

slider.addEventListener('mouseup', () => {

    isDown = false;

    slider.classList.remove('active');
});

slider.addEventListener('mousemove', (e) => {

    if(!isDown) return;

    e.preventDefault();

    const x = e.pageX - slider.offsetLeft;

    const walk = (x - startX) * 2;

    slider.scrollLeft = scrollLeft - walk;
});

</script>

</body>
</html>