<?php  
error_reporting(E_ALL);  
ini_set('display_errors', 1);  
  
require_once('includes/load.php');  

// Database functions
function getPurchaseRequestsForExport() {
    global $db;
    return $db->query("SELECT * FROM purchase_indirect ORDER BY request_number ASC");
}

function getFilteredPurchaseRequests($department_filter, $job_filter, $approval_filter, $order) {
    global $db;
    
    $query = "SELECT * FROM purchase_indirect WHERE 1=1";
    if ($department_filter) $query .= " AND department = '{$department_filter}'";
    if ($job_filter) $query .= " AND job = '{$job_filter}'";
    if ($approval_filter) $query .= " AND status = '{$approval_filter}'";
    $query .= " ORDER BY request_number $order";
    
    return $db->query($query);
}

// Create automatic Request Number  
function generateRequestNumber($db) {  
    $prefix = "REQ";  
    $datePart = date("Ymd");
    $lastIdQuery = $db->query("SELECT id FROM purchase_indirect ORDER BY id DESC LIMIT 1");  
    $lastId = $lastIdQuery->fetch_assoc()['id'] ?? 0;  
    $newId = str_pad($lastId + 1, 4, '0', STR_PAD_LEFT);
    return "{$prefix}-{$datePart}-{$newId}";  
}  
  
$requestNumber = generateRequestNumber($db);  

// Department options for dropdowns
$department_options = [
    'Produksi', 'Maintenance', 'PPIC', 'Purchasing', 'Sales', 'Marketing',
    'Warehouse Bali', 'Warehouse Jakarta', 'Warehouse Surabaya', 
    'Warehouse Makassar', 'Warehouse Semarang', 'Warehouse Bandung',
    'HRGA', 'QC/QA'
];

// Process form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['submit_request'])) {
        // Process purchase request submission
        $request_number = $db->escape($_POST['request_number']);  
        $product_name = $db->escape($_POST['product_name']);  
        $quantity = $db->escape($_POST['quantity']);  
        $uom = $db->escape($_POST['uom']);  
        $department = $db->escape($_POST['department']);  
        $remark = $db->escape($_POST['remark']); 
        $date_needed = $db->escape($_POST['date_needed']); 
        $request_date = date('Y-m-d');  
        $job = "open";
        
        $query = "INSERT INTO purchase_indirect (request_number, product_name, quantity, uom, department, request_date, status, job, remark, date_needed)   
                  VALUES ('{$request_number}', '{$product_name}', '{$quantity}', '{$uom}', '{$department}', '{$request_date}', 'Pending', '{$job}', '{$remark}', '{$date_needed}')";  
        
        if ($db->query($query)) {  
            $session->msg('s', 'Request submitted successfully');  
            redirect('purchase_indirect.php');  
        } else {  
            $session->msg('d', 'Failed to submit request');  
        }  
    } elseif (isset($_POST['update_job'])) {  
        // Process job status update
        $id = $db->escape($_POST['id']);  
        $job = $db->escape($_POST['job']);  
        
        $query = "UPDATE purchase_indirect SET job = '{$job}' WHERE id = '{$id}'";  
        if ($db->query($query)) {  
            $session->msg('s', 'Job status updated successfully');  
            
            // Redirect back with current filters
            $params = [];
            if (!empty($_POST['department_filter'])) $params[] = "department_filter=".$_POST['department_filter'];
            if (!empty($_POST['job_filter'])) $params[] = "job_filter=".$_POST['job_filter'];
            if (!empty($_POST['approval_filter'])) $params[] = "approval_filter=".$_POST['approval_filter'];
            
            $redirect_url = 'purchase_indirect.php';
            if (!empty($params)) {
                $redirect_url .= '?'.implode('&', $params);
            }
            
            redirect($redirect_url);  
        } else {  
            $session->msg('d', 'Failed to update job status');  
        }  
    }  
}  

// Check if the export request is made  
if (isset($_GET['export']) && $_GET['export'] == 'excel') {  
    header('Content-Type: application/vnd.ms-excel');  
    header('Content-Disposition: attachment; filename="purchase_requests.xls"');  
  
    $purchase_requests = getPurchaseRequestsForExport();
  
    // Output the column headings  
    echo "No\tRequest Number\tProduct Name\tQuantity\tUOM\tDepartment\tRequest Date\tDate Needed\tRemark\tApproval\tJob\n";  
  
    $no = 1;  
    while ($row = $purchase_requests->fetch_assoc()) {  
        echo "{$no}\t{$row['request_number']}\t{$row['product_name']}\t{$row['quantity']}\t{$row['uom']}\t{$row['department']}\t" . 
             date('d-m-Y', strtotime($row['request_date'])) . "\t" . 
             (!empty($row['date_needed']) ? date('d-m-Y', strtotime($row['date_needed'])) : '') . 
             "\t{$row['remark']}\t{$row['status']}\t{$row['job']}\n";  
        $no++;  
    }  
    exit;
}  
  
// Determine the sort order  
$order = isset($_GET['order']) && $_GET['order'] == 'desc' ? 'desc' : 'asc';  
$next_order = $order == 'asc' ? 'desc' : 'asc';  
  
// Handle filters - prioritize GET parameters (from redirect) then POST
$department_filter = isset($_GET['department_filter']) ? $db->escape($_GET['department_filter']) : 
                    (isset($_POST['department_filter']) ? $db->escape($_POST['department_filter']) : '');  
$job_filter = isset($_GET['job_filter']) ? $db->escape($_GET['job_filter']) : 
             (isset($_POST['job_filter']) ? $db->escape($_POST['job_filter']) : 'open');
$approval_filter = isset($_GET['approval_filter']) ? $db->escape($_GET['approval_filter']) : 
                  (isset($_POST['approval_filter']) ? $db->escape($_POST['approval_filter']) : '');  
  
// Fetch filtered data
$purchase_requests = getFilteredPurchaseRequests($department_filter, $job_filter, $approval_filter, $order);
?>  
  
<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <meta name="viewport" content="width=device-width, initial-scale=1.0">  
    <title>Purchase Indirect Request System</title>  
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Select2 CSS -->  
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet">
    <!-- Custom CSS -->
    <style>
        :root {
            --primary-color: #3498db;
            --secondary-color: #2c3e50;
            --accent-color: #e74c3c;
            --light-color: #ecf0f1;
            --dark-color: #2c3e50;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f5f7fa;
        }
        
        .navbar-brand {
            font-weight: 700;
            font-size: 1.5rem;
        }
        
        .card {
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
            border: none;
        }
        
        .card-header {
            border-radius: 10px 10px 0 0 !important;
            padding: 15px 20px;
        }
        
        .bg-primary {
            background-color: var(--primary-color) !important;
        }
        
        .bg-info {
            background-color: var(--secondary-color) !important;
        }
        
        .btn-primary {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }
        
        .btn-primary:hover {
            background-color: #2980b9;
            border-color: #2980b9;
        }
        
        .btn-success {
            background-color: #2ecc71;
            border-color: #2ecc71;
        }
        
       .table select {
            padding: 0.25rem 0.5rem;
            height: auto;
            min-width: 100px;
            font-size: 0.9rem;
        }
        
        .table th {
            background-color: var(--light-color);
            font-weight: 600;
        }
        
        .table-responsive {
            overflow-x: auto;
        }
        
        .status-pending {
            color: #f39c12;
            font-weight: bold;
        }
        
        .status-approved {
            color: #2ecc71;
            font-weight: bold;
        }
        
        .status-rejected {
            color: #e74c3c;
            font-weight: bold;
        }
        
        .job-open {
            color: #3498db;
            font-weight: bold;
        }
        
        .job-close {
            color: #7f8c8d;
            font-weight: bold;
        }
        
        .form-label {
            font-weight: 500;
        }
        
        .filter-section {
            background-color: white;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }
        
        .action-buttons .btn {
            margin-right: 5px;
            margin-bottom: 5px;
        }
        
        @media (max-width: 768px) {
            .action-buttons .btn {
                width: 100%;
                margin-bottom: 10px;
            }
        }
    </style>
</head>  
<body>  
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark mb-4">  
        <div class="container">  
            <a class="navbar-brand" href="#">
                <i class="fas fa-shopping-cart me-2"></i>Purchase Request System
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="dashboard_purchase_indirect.php">
                            <i class="fas fa-tachometer-alt me-1"></i> Dashboard
                        </a>
                    </li>
                </ul>
            </div>
        </div>  
    </nav>  
  
    <div class="container">  
        <!-- Request Submission Form -->
        <div class="row">  
            <div class="col-lg-12">  
                <div class="card">  
                    <div class="card-header bg-primary text-white">  
                        <h4 class="card-title mb-0"><i class="fas fa-plus-circle me-2"></i>New Purchase Request</h4>  
                    </div>  
                    <div class="card-body">  
                        <form method="post" action="purchase_indirect.php">  
                            <div class="row g-3 mb-4">  
                                <div class="col-md-4">  
                                    <label for="request_number" class="form-label">Request Number</label>  
                                    <input type="text" name="request_number" id="request_number" class="form-control"  
                                        value="<?= $requestNumber ?>" readonly>  
                                </div>  
                                <div class="col-md-4">  
                                    <label for="product_name" class="form-label">Product Name</label>  
                                    <select name="product_name" id="product_name" class="form-control select2" required>  
                                        <option value="">Select Product</option>  
                                    </select>  
                                </div>  
                                <div class="col-md-2">  
                                    <label for="quantity" class="form-label">Quantity</label>  
                                    <input type="number" name="quantity" id="quantity" class="form-control" min="1" required>  
                                </div>  
                                <div class="col-md-2">  
                                    <label for="uom" class="form-label">UOM</label>  
                                    <input type="text" name="uom" id="uom" class="form-control" required>  
                                </div>  
                            </div>  
  
                            <div class="row g-3 mb-4">  
                                <div class="col-md-4">  
                                    <label for="department" class="form-label">Department</label>  
                                    <select name="department" id="department" class="form-select" required>  
                                        <?php foreach ($department_options as $dept): ?>
                                            <option value="<?= $dept ?>"><?= $dept ?></option>  
                                        <?php endforeach; ?>
                                    </select>  
                                </div>  
                                <div class="col-md-4">  
                                    <label for="date_needed" class="form-label">Date Needed</label>  
                                    <input type="date" name="date_needed" id="date_needed" class="form-control" required 
                                           min="<?= date('Y-m-d') ?>">  
                                </div>  
                                <div class="col-md-4">  
                                    <label for="remark" class="form-label">Remark</label>  
                                    <input type="text" name="remark" id="remark" class="form-control" placeholder="Optional">  
                                </div>  
                            </div>  
  
                            <div class="d-flex flex-wrap justify-content-between align-items-center action-buttons">  
                                <button type="submit" name="submit_request" class="btn btn-primary btn-lg">
                                    <i class="fas fa-paper-plane me-2"></i>Submit Request
                                </button>  
                                <div class="d-flex flex-wrap">
                                    <a href="list_indirect.php" class="btn btn-outline-secondary me-2">
                                        <i class="fas fa-list me-2"></i>List Data Indirect
                                    </a>  
                                    <a href="create_indirect_code.php" class="btn btn-outline-secondary me-2">
                                        <i class="fas fa-plus me-2"></i>Create Item
                                    </a>  
                                    <a href="purchase_indirect.php?export=excel" class="btn btn-success">
                                        <i class="fas fa-file-excel me-2"></i>Export to Excel
                                    </a>  
                                </div>
                            </div>  
                        </form>  
                    </div>  
                </div>  
            </div>  
        </div>  
  
        <!-- Request List Section -->
        <div class="row">  
            <div class="col-lg-12">  
                <div class="card">  
                    <div class="card-header bg-info text-white">  
                        <h4 class="card-title mb-0"><i class="fas fa-clipboard-list me-2"></i>Purchase Requests</h4>  
                    </div>  
                    <div class="card-body">  
                        <!-- Filter Section -->
                        <form method="post" action="purchase_indirect.php" class="filter-section">  
                            <div class="row g-3">  
                                <div class="col-md-3">  
                                    <label for="department_filter" class="form-label">Department</label>  
                                    <select name="department_filter" id="department_filter" class="form-select">  
                                        <option value="">All Departments</option>  
                                        <?php foreach ($department_options as $dept): ?>
                                            <option value="<?= $dept ?>" <?= $department_filter == $dept ? 'selected' : '' ?>>
                                                <?= $dept ?>
                                            </option>  
                                        <?php endforeach; ?>
                                    </select>  
                                </div>  
                                <div class="col-md-3">  
                                    <label for="job_filter" class="form-label">Job Status</label>  
                                    <select name="job_filter" id="job_filter" class="form-select">  
                                        <option value="open" <?= $job_filter == 'open' ? 'selected' : '' ?>>Open</option>  
                                        <option value="close" <?= $job_filter == 'close' ? 'selected' : '' ?>>Closed</option>  
                                        <option value="">All Statuses</option>  
                                    </select>  
                                </div>  
                                <div class="col-md-3">  
                                    <label for="approval_filter" class="form-label">Approval Status</label>  
                                    <select name="approval_filter" id="approval_filter" class="form-select">  
                                        <option value="">All Statuses</option>  
                                        <option value="approved" <?= $approval_filter == 'approved' ? 'selected' : '' ?>>Approved</option>  
                                        <option value="rejected" <?= $approval_filter == 'rejected' ? 'selected' : '' ?>>Rejected</option>  
                                        <option value="pending" <?= $approval_filter == 'pending' ? 'selected' : '' ?>>Pending</option>  
                                    </select>  
                                </div>  
                                <div class="col-md-3 d-flex align-items-end">  
                                    <button type="submit" class="btn btn-primary w-100">
                                        <i class="fas fa-filter me-2"></i>Apply Filters
                                    </button>  
                                </div>  
                            </div>  
                        </form>  
                        
                        <!-- Request Table -->
                        <div class="table-responsive">  
                            <table class="table table-hover align-middle">  
                                <thead>  
                                    <tr>  
                                        <th width="50">No</th>  
                                        <th>
                                            <a href="?order=<?= $next_order ?><?= !empty($department_filter) ? '&department_filter='.$department_filter : '' ?><?= !empty($job_filter) ? '&job_filter='.$job_filter : '' ?><?= !empty($approval_filter) ? '&approval_filter='.$approval_filter : '' ?>" class="text-decoration-none">
                                                Request Number
                                                <i class="fas fa-sort<?= $order == 'asc' ? '-up' : '-down' ?> ms-1"></i>
                                            </a>
                                        </th>  
                                        <th>Product</th>  
                                        <th>Qty</th>  
                                        <th>UOM</th>  
                                        <th>Department</th>  
                                        <th>Request Date</th>  
                                        <th>Date Needed</th>  
                                        <th>Remark</th>  
                                        <th>Approval</th>  
                                        <th>Status</th>  
                                    </tr>  
                                </thead>  
                                <tbody>  
                                    <?php if ($purchase_requests->num_rows > 0): ?>
                                        <?php $no = 1; ?>
                                        <?php while ($row = $purchase_requests->fetch_assoc()): ?>  
                                            <tr>  
                                                <td><?= $no++ ?></td>  
                                                <td>
                                                    <span class="fw-bold"><?= $row['request_number'] ?></span>
                                                </td>  
                                                <td><?= htmlspecialchars($row['product_name']) ?></td>  
                                                <td><?= $row['quantity'] ?></td>  
                                                <td><?= $row['uom'] ?></td>  
                                                <td><?= $row['department'] ?></td>  
                                                <td><?= date('d M Y', strtotime($row['request_date'])) ?></td>  
                                                <td>
                                                    <?= !empty($row['date_needed']) ? date('d M Y', strtotime($row['date_needed'])) : '-' ?>  
                                                </td>  
                                                <td><?= !empty($row['remark']) ? htmlspecialchars($row['remark']) : '-' ?></td>  
                                                <td class="status-<?= strtolower($row['status']) ?>">
                                                    <?= ucfirst($row['status']) ?>
                                                </td>  
                                                <td>  
                                                    <form method="post" action="purchase_indirect.php" class="d-inline">  
                                                        <input type="hidden" name="id" value="<?= $row['id'] ?>">  
                                                        <input type="hidden" name="department_filter" value="<?= $department_filter ?>">
                                                        <input type="hidden" name="job_filter" value="<?= $job_filter ?>">
                                                        <input type="hidden" name="approval_filter" value="<?= $approval_filter ?>">
                                                        <select name="job" onchange="this.form.submit()" class="form-select form-select-sm job-<?= $row['job'] ?>">
                                                            <option value="open" <?= $row['job'] == 'open' ? 'selected' : '' ?>>Open</option>  
                                                            <option value="close" <?= $row['job'] == 'close' ? 'selected' : '' ?>>Closed</option>  
                                                        </select>  
                                                        <input type="hidden" name="update_job" value="1">  
                                                    </form>  
                                                </td>  
                                            </tr>  
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="11" class="text-center py-4 text-muted">
                                                <i class="fas fa-inbox fa-2x mb-3"></i>
                                                <p class="mb-0">No purchase requests found</p>
                                                <?php if ($department_filter || $job_filter || $approval_filter): ?>
                                                    <small class="d-block mt-2">Try adjusting your filters</small>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>  
                            </table>  
                        </div>  
                    </div>  
                </div>  
            </div>  
        </div>  
    </div>  
  
    <!-- JavaScript Libraries -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>  
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    
    <script>  
        $(document).ready(function() {  
            // Initialize Select2 for product search
            $(".select2").select2({
                ajax: {  
                    url: "get_indirect_names.php",  
                    dataType: "json",  
                    delay: 250,  
                    data: function (params) {  
                        return { term: params.term };  
                    },  
                    processResults: function (data) {  
                        return {  
                            results: data.map(function (item) {  
                                return { id: item, text: item };  
                            })  
                        };  
                    }  
                },  
                minimumInputLength: 2
            });
            
            // Set minimum date for date_needed field
            $('#date_needed').attr('min', new Date().toISOString().split('T')[0]);
            
            // Add animation to table rows
            $('table tbody tr').hover(
                function() {
                    $(this).addClass('shadow-sm');
                },
                function() {
                    $(this).removeClass('shadow-sm');
                }
            );
        });  
    </script>  
</body>  
</html>