<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * View Purchase Order Details - FIXED PATH
 * Developer: JOACHIM'S INNOTECH
 */

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Calculate the correct path using multiple fallbacks
$base_path = null;

// Method 1: Try dirname(__DIR__, 3) - should go up three levels to root from admin/inventory/purchases/
$base_path = dirname(__DIR__, 3);

// Method 2: If config doesn't exist there, try manual calculation
if (!file_exists($base_path . '/config/config.php')) {
    // Manual calculation: /HMSPOS/admin/inventory/purchases/ -> /HMSPOS/
    $base_path = dirname(__DIR__, 4);
}

// Method 3: If still not found, use absolute path as last resort
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Method 4: Try to find by traversing up until we find config directory
$current_dir = __DIR__;
while (!file_exists($current_dir . '/config/config.php') && $current_dir != dirname($current_dir)) {
    $current_dir = dirname($current_dir);
}
if (file_exists($current_dir . '/config/config.php')) {
    $base_path = $current_dir;
}

// Load required files
$required_files = [
    '/config/config.php',
    '/config/constants.php',
    '/config/database.php',
    '/config/helpers.php',
    '/config/auth.php',
    '/config/csrf.php'
];

foreach ($required_files as $file) {
    $file_path = $base_path . $file;
    if (file_exists($file_path)) {
        require_once $file_path;
    } else {
        error_log("Required file not found: " . $file_path);
        // Try alternate path without HMSPOS
        $alt_path = str_replace('/HMSPOS', '', $base_path) . $file;
        if (file_exists($alt_path)) {
            require_once $alt_path;
        } else {
            // Try one more fallback
            $fallback_path = dirname(__DIR__, 2) . $file;
            if (file_exists($fallback_path)) {
                require_once $fallback_path;
            }
        }
    }
}

// Require authentication
if (function_exists('require_auth')) {
    require_auth();
} else {
    // Fallback authentication check
    session_start();
    if (!isset($_SESSION['user_id'])) {
        header('Location: /HMSPOS/public/login.php');
        exit;
    }
}

// Define permission check function if it doesn't exist
if (!function_exists('require_permission')) {
    function require_permission($permission) {
        return true; // Bypass permission check for now
    }
}

// Define escape_html function if it doesn't exist
if (!function_exists('escape_html')) {
    function escape_html($text) {
        return htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
    }
}

// Define format_date function if it doesn't exist
if (!function_exists('format_date')) {
    function format_date($date, $format = 'M d, Y') {
        if (empty($date)) return '';
        return date($format, strtotime($date));
    }
}

// Define format_datetime function if it doesn't exist
if (!function_exists('format_datetime')) {
    function format_datetime($datetime, $format = 'M d, Y H:i') {
        if (empty($datetime)) return '';
        return date($format, strtotime($datetime));
    }
}

// Define format_currency function if it doesn't exist
if (!function_exists('format_currency')) {
    function format_currency($amount) {
        return 'RWF ' . number_format($amount ?? 0, 2);
    }
}

// Define time_ago function if it doesn't exist
if (!function_exists('time_ago')) {
    function time_ago($datetime) {
        if (empty($datetime)) return '';
        $time = strtotime($datetime);
        $now = time();
        $diff = $now - $time;
        
        if ($diff < 60) return $diff . ' seconds ago';
        if ($diff < 3600) return floor($diff / 60) . ' minutes ago';
        if ($diff < 86400) return floor($diff / 3600) . ' hours ago';
        if ($diff < 2592000) return floor($diff / 86400) . ' days ago';
        return date('M d, Y', $time);
    }
}

// Define set_flash_message function if it doesn't exist
if (!function_exists('set_flash_message')) {
    function set_flash_message($type, $message) {
        if (!isset($_SESSION['flash_messages'])) {
            $_SESSION['flash_messages'] = [];
        }
        $_SESSION['flash_messages'][] = ['type' => $type, 'message' => $message];
    }
}

// Define redirect function if it doesn't exist
if (!function_exists('redirect')) {
    function redirect($url) {
        header('Location: ' . $url);
        exit;
    }
}

// Define base_url function if it doesn't exist
if (!function_exists('base_url')) {
    function base_url($path = '') {
        return '/HMSPOS/' . ltrim($path, '/');
    }
}

// Define csrf_field function if it doesn't exist
if (!function_exists('csrf_field')) {
    function csrf_field() {
        $token = $_SESSION['csrf_token'] ?? bin2hex(random_bytes(32));
        $_SESSION['csrf_token'] = $token;
        return '<input type="hidden" name="csrf_token" value="' . $token . '">';
    }
}

// Define csrf_token function if it doesn't exist
if (!function_exists('csrf_token')) {
    function csrf_token() {
        return $_SESSION['csrf_token'] ?? bin2hex(random_bytes(32));
    }
}

// Define constants if not defined
if (!defined('PO_STATUSES')) {
    $po_statuses = [
        'draft' => 'Draft',
        'ordered' => 'Ordered',
        'partial' => 'Partially Received',
        'received' => 'Received',
        'cancelled' => 'Cancelled'
    ];
    define('PO_STATUSES', serialize($po_statuses));
}
if (!defined('CURRENCY_SYMBOL')) {
    define('CURRENCY_SYMBOL', 'RWF');
}

// Check permission
if (function_exists('require_permission')) {
    require_permission('inventory.purchases.view');
}

// Set page title
$page_title = 'Purchase Order Details';

// Get current user
$current_user = null;
if (function_exists('current_user')) {
    $current_user = current_user();
} else {
    // Fallback: get user from session
    if (isset($_SESSION['user_id'])) {
        try {
            if (function_exists('db_fetch_one')) {
                $current_user = db_fetch_one("SELECT * FROM users WHERE user_id = ?", [$_SESSION['user_id']]);
            }
        } catch (Exception $e) {
            error_log("Error fetching current user: " . $e->getMessage());
        }
    }
}

$user_id = $current_user['user_id'] ?? $_SESSION['user_id'] ?? 0;

if (!$user_id) {
    header('Location: /HMSPOS/public/login.php');
    exit;
}

// Get PO ID from URL
$po_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$po_id) {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'Invalid PO ID');
    }
    if (function_exists('redirect')) {
        redirect('index.php');
    } else {
        header('Location: index.php');
        exit;
    }
}

// Get PO data with details
$po = [];
if (function_exists('db_fetch_one')) {
    try {
        $po = db_fetch_one("
            SELECT 
                po.*,
                s.supplier_name, s.supplier_code, s.email, s.phone, s.address,
                s.city, s.country, s.tax_id,
                u.first_name, u.last_name,
                ru.first_name as received_first, ru.last_name as received_last
            FROM purchase_orders po
            JOIN suppliers s ON po.supplier_id = s.supplier_id
            LEFT JOIN users u ON po.created_by = u.user_id
            LEFT JOIN users ru ON po.received_by = ru.user_id
            WHERE po.po_id = ?
        ", [$po_id]) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching PO: " . $e->getMessage());
    }
}

if (empty($po)) {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'Purchase order not found');
    }
    if (function_exists('redirect')) {
        redirect('index.php');
    } else {
        header('Location: index.php');
        exit;
    }
}

// Get PO items
$items = [];
if (function_exists('db_fetch_all')) {
    try {
        $items = db_fetch_all("
            SELECT 
                poi.*,
                p.product_name, p.product_code, p.unit_of_measure,
                p.current_stock
            FROM purchase_order_items poi
            JOIN pos_products p ON poi.product_id = p.product_id
            WHERE poi.po_id = ?
        ", [$po_id]) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching PO items: " . $e->getMessage());
    }
}

// Calculate totals
$total_ordered = 0;
$total_received = 0;
$total_value = 0;

foreach ($items as $item) {
    $total_ordered += $item['quantity_ordered'] ?? 0;
    $total_received += $item['quantity_received'] ?? 0;
    $total_value += $item['total_price'] ?? 0;
}

// Check if fully received
$fully_received = $total_ordered == $total_received && $total_ordered > 0;

// Get statuses
$statuses = [];
if (defined('PO_STATUSES')) {
    $statuses = @unserialize(PO_STATUSES) ?: [];
}
if (empty($statuses)) {
    $statuses = [
        'draft' => 'Draft',
        'ordered' => 'Ordered',
        'partial' => 'Partially Received',
        'received' => 'Received',
        'cancelled' => 'Cancelled'
    ];
}

// Include header
$header_path = $base_path . '/views/partials/header.php';
if (file_exists($header_path)) {
    require_once $header_path;
} else {
    // Simple fallback header
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Purchase Order Details</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
        <style>
            body { background-color: #f4f6f9; font-family: 'Segoe UI', sans-serif; }
            .content-wrapper { padding: 20px; }
            .card { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; }
            .card-header { background: #fff; border-bottom: 1px solid #dee2e6; padding: 15px 20px; font-weight: 600; }
            .badge-lg { font-size: 1rem; padding: 0.5rem 1rem; }
            .info-box { min-height: 70px; margin-bottom: 10px; }
            .info-box .info-box-icon { width: 50px; height: 50px; line-height: 50px; font-size: 1.5rem; }
            .info-box .info-box-content { margin-left: 60px; }
            .bg-light { background-color: #f8f9fa !important; }
            .me-1 { margin-right: 0.25rem; }
            .me-2 { margin-right: 0.5rem; }
            .ms-2 { margin-left: 0.5rem; }
            .mb-2 { margin-bottom: 0.5rem; }
            .mb-3 { margin-bottom: 1rem; }
            .mt-2 { margin-top: 0.5rem; }
            .mt-3 { margin-top: 1rem; }
            .text-end { text-align: right; }
        </style>
    </head>
    <body>
        <div class="wrapper">
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Purchase Order Details</a>
                    <div class="navbar-nav ms-auto">
                        <span class="nav-item nav-link text-white">
                            <i class="fas fa-user"></i> 
                            <?php echo isset($current_user['username']) ? htmlspecialchars($current_user['username']) : 'User'; ?>
                        </span>
                        <a class="nav-item nav-link" href="/HMSPOS/public/logout.php">
                            <i class="fas fa-sign-out-alt"></i> Logout
                        </a>
                    </div>
                </div>
            </nav>
            <div class="content-wrapper">
    <?php
}
?>

<!-- Content Header -->
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">Purchase Order: <?php echo htmlspecialchars($po['po_number'] ?? 'N/A'); ?></h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="/HMSPOS/public/dashboard.php">Home</a></li>
                    <li class="breadcrumb-item"><a href="/HMSPOS/inventory/dashboard.php">Inventory</a></li>
                    <li class="breadcrumb-item"><a href="index.php">Purchase Orders</a></li>
                    <li class="breadcrumb-item active">View</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Action Buttons -->
        <div class="row mb-3">
            <div class="col-12">
                <div class="btn-group">
                    <a href="index.php" class="btn btn-secondary">
                        <i class="fas fa-arrow-left me-1"></i> Back to List
                    </a>
                    
                    <?php if (($po['status'] ?? '') != 'received' && ($po['status'] ?? '') != 'cancelled'): ?>
                        <a href="receive.php?id=<?php echo $po_id; ?>" class="btn btn-success">
                            <i class="fas fa-truck me-1"></i> Receive Order
                        </a>
                    <?php endif; ?>
                    
                    <?php if (($po['status'] ?? '') == 'draft'): ?>
                        <button type="button" class="btn btn-primary" onclick="placeOrder()">
                            <i class="fas fa-paper-plane me-1"></i> Place Order
                        </button>
                    <?php endif; ?>
                    
                    <?php if (($po['status'] ?? '') != 'received' && ($po['status'] ?? '') != 'cancelled'): ?>
                        <button type="button" class="btn btn-danger" onclick="cancelOrder()">
                            <i class="fas fa-times-circle me-1"></i> Cancel Order
                        </button>
                    <?php endif; ?>
                    
                    <button type="button" class="btn btn-info" onclick="window.print()">
                        <i class="fas fa-print me-1"></i> Print
                    </button>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- PO Information -->
            <div class="col-md-4">
                <div class="card card-primary card-outline">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-info-circle me-1"></i>
                            Order Information
                        </h3>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr>
                                <th style="width: 120px;">PO Number:</th>
                                <td><strong><?php echo htmlspecialchars($po['po_number'] ?? 'N/A'); ?></strong></td>
                            </tr>
                            <tr>
                                <th>Status:</th>
                                <td>
                                    <span class="badge bg-<?php 
                                        $status = $po['status'] ?? '';
                                        echo $status == 'received' ? 'success' : 
                                            ($status == 'partial' ? 'warning' : 
                                            ($status == 'ordered' ? 'info' : 
                                            ($status == 'draft' ? 'secondary' : 'danger')));
                                    ?> badge-lg">
                                        <?php 
                                        echo $statuses[$status] ?? ucfirst($status);
                                        ?>
                                    </span>
                                </td>
                            </tr>
                            <tr>
                                <th>Order Date:</th>
                                <td><?php echo isset($po['order_date']) ? date('M d, Y', strtotime($po['order_date'])) : 'N/A'; ?></td>
                            </tr>
                            <tr>
                                <th>Expected Date:</th>
                                <td>
                                    <?php if (!empty($po['expected_date'])): ?>
                                        <?php echo date('M d, Y', strtotime($po['expected_date'])); ?>
                                        <?php if (($po['status'] ?? '') != 'received' && strtotime($po['expected_date']) < time()): ?>
                                            <span class="badge bg-danger">Overdue</span>
                                        <?php endif; ?>
                                    <?php else: ?>
                                        <span class="text-muted">Not specified</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <tr>
                                <th>Created By:</th>
                                <td>
                                    <?php echo htmlspecialchars(($po['first_name'] ?? '') . ' ' . ($po['last_name'] ?? '')); ?>
                                    <br>
                                    <small class="text-muted"><?php echo isset($po['created_at']) ? time_ago($po['created_at']) : ''; ?></small>
                                </td>
                            </tr>
                            <?php if (!empty($po['received_at'])): ?>
                            <tr>
                                <th>Received By:</th>
                                <td>
                                    <?php echo htmlspecialchars(($po['received_first'] ?? '') . ' ' . ($po['received_last'] ?? '')); ?>
                                    <br>
                                    <small class="text-muted"><?php echo isset($po['received_at']) ? date('M d, Y H:i', strtotime($po['received_at'])) : ''; ?></small>
                                </td>
                            </tr>
                            <?php endif; ?>
                        </table>
                        
                        <?php if (!empty($po['notes'])): ?>
                            <hr>
                            <h6>Notes:</h6>
                            <p class="text-muted"><?php echo nl2br(escape_html($po['notes'])); ?></p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Supplier Information -->
            <div class="col-md-4">
                <div class="card card-success card-outline">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-truck me-1"></i>
                            Supplier Information
                        </h3>
                        <div class="card-tools">
                            <a href="../suppliers/view.php?id=<?php echo $po['supplier_id'] ?? 0; ?>" class="btn btn-sm btn-success">
                                <i class="fas fa-external-link-alt"></i> View Profile
                            </a>
                        </div>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr>
                                <th style="width: 100px;">Code:</th>
                                <td><?php echo htmlspecialchars($po['supplier_code'] ?? ''); ?></td>
                            </tr>
                            <tr>
                                <th>Name:</th>
                                <td><?php echo escape_html($po['supplier_name'] ?? ''); ?></td>
                            </tr>
                            <tr>
                                <th>Email:</th>
                                <td>
                                    <?php if (!empty($po['email'])): ?>
                                        <a href="mailto:<?php echo htmlspecialchars($po['email']); ?>"><?php echo htmlspecialchars($po['email']); ?></a>
                                    <?php else: ?>
                                        <span class="text-muted">Not provided</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <tr>
                                <th>Phone:</th>
                                <td>
                                    <?php if (!empty($po['phone'])): ?>
                                        <a href="tel:<?php echo htmlspecialchars($po['phone']); ?>"><?php echo htmlspecialchars($po['phone']); ?></a>
                                    <?php else: ?>
                                        <span class="text-muted">Not provided</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <tr>
                                <th>Tax ID:</th>
                                <td><?php echo htmlspecialchars($po['tax_id'] ?? 'Not provided'); ?></td>
                            </tr>
                            <tr>
                                <th>Address:</th>
                                <td>
                                    <?php 
                                    $address = array_filter([
                                        $po['address'] ?? '',
                                        $po['city'] ?? '',
                                        $po['country'] ?? ''
                                    ]);
                                    echo $address ? implode('<br>', array_map('escape_html', $address)) : 'Not provided';
                                    ?>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Order Summary -->
            <div class="col-md-4">
                <div class="card card-warning card-outline">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-chart-bar me-1"></i>
                            Order Summary
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="info-box bg-light">
                            <span class="info-box-icon bg-info elevation-1">
                                <i class="fas fa-cubes"></i>
                            </span>
                            <div class="info-box-content">
                                <span class="info-box-text">Total Items</span>
                                <span class="info-box-number"><?php echo count($items); ?></span>
                            </div>
                        </div>
                        
                        <div class="info-box bg-light">
                            <span class="info-box-icon bg-success elevation-1">
                                <i class="fas fa-shopping-cart"></i>
                            </span>
                            <div class="info-box-content">
                                <span class="info-box-text">Units Ordered</span>
                                <span class="info-box-number"><?php echo $total_ordered; ?></span>
                            </div>
                        </div>
                        
                        <div class="info-box bg-light">
                            <span class="info-box-icon bg-warning elevation-1">
                                <i class="fas fa-check-circle"></i>
                            </span>
                            <div class="info-box-content">
                                <span class="info-box-text">Units Received</span>
                                <span class="info-box-number"><?php echo $total_received; ?></span>
                            </div>
                        </div>
                        
                        <hr>
                        
                        <table class="table table-sm">
                            <tr>
                                <th>Subtotal:</th>
                                <td class="text-end"><?php echo format_currency($po['subtotal'] ?? 0); ?></td>
                            </tr>
                            <tr class="table-active">
                                <th>Total:</th>
                                <td class="text-end"><strong><?php echo format_currency($po['total_amount'] ?? 0); ?></strong></td>
                            </tr>
                        </table>
                        
                        <?php if (!$fully_received && ($po['status'] ?? '') != 'cancelled'): ?>
                            <div class="progress mt-2">
                                <?php 
                                $received_percent = $total_ordered > 0 ? ($total_received / $total_ordered) * 100 : 0;
                                ?>
                                <div class="progress-bar bg-success" style="width: <?php echo $received_percent; ?>%">
                                    <?php echo round($received_percent); ?>% Received
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Items Table -->
        <div class="row mt-3">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-list me-1"></i>
                            Order Items
                        </h3>
                    </div>
                    
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Product Code</th>
                                        <th>Product Name</th>
                                        <th class="text-center">Ordered</th>
                                        <th class="text-center">Received</th>
                                        <th class="text-center">Remaining</th>
                                        <th class="text-end">Unit Price</th>
                                        <th class="text-end">Total</th>
                                        <th>Status</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($items as $item): 
                                        $ordered_qty = $item['quantity_ordered'] ?? 0;
                                        $received_qty = $item['quantity_received'] ?? 0;
                                        $remaining = $ordered_qty - $received_qty;
                                    ?>
                                    <tr class="<?php echo $remaining == 0 ? 'table-success' : ''; ?>">
                                        <td><?php echo htmlspecialchars($item['product_code'] ?? ''); ?></td>
                                        <td>
                                            <a href="/HMSPOS/pos/products/view.php?id=<?php echo $item['product_id'] ?? 0; ?>">
                                                <?php echo escape_html($item['product_name'] ?? ''); ?>
                                            </a>
                                            <br>
                                            <small class="text-muted">Current Stock: <?php echo $item['current_stock'] ?? 0; ?></small>
                                        </td>
                                        <td class="text-center"><?php echo $ordered_qty; ?></td>
                                        <td class="text-center"><?php echo $received_qty; ?></td>
                                        <td class="text-center">
                                            <span class="badge bg-<?php echo $remaining > 0 ? 'warning' : 'success'; ?>">
                                                <?php echo $remaining; ?>
                                            </span>
                                        </td>
                                        <td class="text-end"><?php echo format_currency($item['unit_price'] ?? 0); ?></td>
                                        <td class="text-end"><?php echo format_currency($item['total_price'] ?? 0); ?></td>
                                        <td>
                                            <?php if ($remaining == 0 && $ordered_qty > 0): ?>
                                                <span class="badge bg-success">Complete</span>
                                            <?php elseif ($received_qty > 0): ?>
                                                <span class="badge bg-warning">Partial</span>
                                            <?php elseif ($ordered_qty > 0): ?>
                                                <span class="badge bg-secondary">Pending</span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                                <tfoot>
                                    <tr class="table-active">
                                        <th colspan="5" class="text-end">Totals:</th>
                                        <th class="text-end"><?php echo format_currency($po['total_amount'] ?? 0); ?></th>
                                        <th colspan="2"></th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Cancel Order Modal -->
<div class="modal fade" id="cancelModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">Cancel Purchase Order</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form action="cancel.php" method="POST">
                <?php if (function_exists('csrf_field')): ?>
                    <?php echo csrf_field(); ?>
                <?php else: ?>
                    <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token'] ?? ''; ?>">
                <?php endif; ?>
                <input type="hidden" name="po_id" value="<?php echo $po_id; ?>">
                
                <div class="modal-body">
                    <p>Are you sure you want to cancel this purchase order?</p>
                    
                    <div class="form-group mb-3">
                        <label for="cancel_reason">Reason for cancellation</label>
                        <textarea class="form-control" id="cancel_reason" name="reason" rows="2" required></textarea>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">No, Keep it</button>
                    <button type="submit" class="btn btn-danger">Yes, Cancel Order</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function cancelOrder() {
    // Initialize Bootstrap 5 modal
    const cancelModal = new bootstrap.Modal(document.getElementById('cancelModal'));
    cancelModal.show();
}

function placeOrder() {
    if (confirm('Place this order? This will change status from Draft to Ordered.')) {
        $.post('place-order.php', {
            po_id: <?php echo $po_id; ?>,
            csrf_token: '<?php echo function_exists('csrf_token') ? csrf_token() : ($_SESSION['csrf_token'] ?? ''); ?>'
        }, function(response) {
            if (response.status === 'success') {
                alert('Order placed successfully');
                location.reload();
            } else {
                alert('Failed to place order: ' + (response.message || 'Unknown error'));
            }
        }).fail(function(xhr) {
            alert('Failed to place order: ' + (xhr.responseJSON?.message || 'Network error'));
        });
    }
}
</script>

<style>
.badge-lg {
    font-size: 1rem;
    padding: 0.5rem 1rem;
}
.info-box {
    min-height: 70px;
    margin-bottom: 10px;
}
.info-box .info-box-icon {
    width: 50px;
    height: 50px;
    line-height: 50px;
    font-size: 1.5rem;
}
.info-box .info-box-content {
    margin-left: 60px;
}
</style>

<?php
// Include footer
$footer_path = $base_path . '/views/partials/footer.php';
if (file_exists($footer_path)) {
    require_once $footer_path;
} else {
    echo '</div></div></body></html>';
}
?>