<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * View Supplier 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/suppliers/
$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/suppliers/ -> /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 has_permission function if it doesn't exist
if (!function_exists('has_permission')) {
    function has_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_currency function if it doesn't exist
if (!function_exists('format_currency')) {
    function format_currency($amount) {
        return 'RWF ' . number_format($amount ?? 0, 2);
    }
}

// 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, '/');
    }
}

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

// Set page title
$page_title = 'Supplier 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 supplier ID from URL
$supplier_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

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

// Get supplier data
$supplier = [];
if (function_exists('db_fetch_one')) {
    try {
        $supplier = db_fetch_one("SELECT * FROM suppliers WHERE supplier_id = ?", [$supplier_id]) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching supplier: " . $e->getMessage());
    }
}

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

// Get purchase statistics
$stats = [
    'total_pos' => 0,
    'total_spent' => 0,
    'pending_pos' => 0,
    'avg_po_value' => 0,
    'first_order' => null,
    'last_order' => null
];

if (function_exists('db_fetch_value')) {
    try {
        $stats['total_pos'] = db_fetch_value("SELECT COUNT(*) FROM purchase_orders WHERE supplier_id = ?", [$supplier_id]) ?: 0;
        $stats['total_spent'] = db_fetch_value("SELECT COALESCE(SUM(total_amount), 0) FROM purchase_orders WHERE supplier_id = ?", [$supplier_id]) ?: 0;
        $stats['pending_pos'] = db_fetch_value("SELECT COUNT(*) FROM purchase_orders WHERE supplier_id = ? AND status IN ('ordered', 'partial')", [$supplier_id]) ?: 0;
        $stats['avg_po_value'] = db_fetch_value("SELECT COALESCE(AVG(total_amount), 0) FROM purchase_orders WHERE supplier_id = ?", [$supplier_id]) ?: 0;
        $stats['first_order'] = db_fetch_value("SELECT MIN(order_date) FROM purchase_orders WHERE supplier_id = ?", [$supplier_id]);
        $stats['last_order'] = db_fetch_value("SELECT MAX(order_date) FROM purchase_orders WHERE supplier_id = ?", [$supplier_id]);
    } catch (Exception $e) {
        error_log("Error fetching stats: " . $e->getMessage());
    }
}

// Get recent purchase orders
$recent_pos = [];
if (function_exists('db_fetch_all')) {
    try {
        $recent_pos = db_fetch_all("
            SELECT 
                po.*,
                COUNT(poi.item_id) as item_count
            FROM purchase_orders po
            LEFT JOIN purchase_order_items poi ON po.po_id = poi.po_id
            WHERE po.supplier_id = ?
            GROUP BY po.po_id
            ORDER BY po.order_date DESC
            LIMIT 10
        ", [$supplier_id]) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching recent POs: " . $e->getMessage());
    }
}

// Get products commonly purchased from this supplier
$common_products = [];
if (function_exists('db_fetch_all')) {
    try {
        $common_products = db_fetch_all("
            SELECT 
                p.product_id, p.product_name, p.product_code,
                COUNT(DISTINCT po.po_id) as order_count,
                SUM(poi.quantity_ordered) as total_ordered,
                AVG(poi.unit_price) as avg_price
            FROM pos_products p
            JOIN purchase_order_items poi ON p.product_id = poi.product_id
            JOIN purchase_orders po ON poi.po_id = po.po_id
            WHERE po.supplier_id = ?
            GROUP BY p.product_id
            ORDER BY order_count DESC
            LIMIT 10
        ", [$supplier_id]) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching common products: " . $e->getMessage());
    }
}

// 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>Supplier 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; }
            .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="#">Supplier 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">Supplier: <?php echo escape_html($supplier['supplier_name'] ?? ''); ?></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">Suppliers</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 (function_exists('has_permission') && has_permission('inventory.suppliers.manage')): ?>
                        <a href="edit.php?id=<?php echo $supplier_id; ?>" class="btn btn-warning">
                            <i class="fas fa-edit me-1"></i> Edit Supplier
                        </a>
                    <?php endif; ?>
                    
                    <a href="../purchases/create-po.php?supplier_id=<?php echo $supplier_id; ?>" class="btn btn-success">
                        <i class="fas fa-plus-circle me-1"></i> Create Purchase Order
                    </a>
                    
                    <a href="../purchases/index.php?supplier_id=<?php echo $supplier_id; ?>" class="btn btn-info">
                        <i class="fas fa-list me-1"></i> View All POs
                    </a>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Supplier 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>
                            Supplier Information
                        </h3>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr>
                                <th style="width: 120px;">Code:</th>
                                <td><strong><?php echo htmlspecialchars($supplier['supplier_code'] ?? ''); ?></strong></td>
                            </tr>
                            <tr>
                                <th>Name:</th>
                                <td><?php echo escape_html($supplier['supplier_name'] ?? ''); ?></td>
                            </tr>
                            <tr>
                                <th>Contact Person:</th>
                                <td><?php echo escape_html($supplier['contact_person'] ?? 'Not specified'); ?></td>
                            </tr>
                            <tr>
                                <th>Email:</th>
                                <td>
                                    <?php if (!empty($supplier['email'])): ?>
                                        <a href="mailto:<?php echo htmlspecialchars($supplier['email']); ?>"><?php echo htmlspecialchars($supplier['email']); ?></a>
                                    <?php else: ?>
                                        <span class="text-muted">Not provided</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <tr>
                                <th>Phone:</th>
                                <td>
                                    <?php if (!empty($supplier['phone'])): ?>
                                        <a href="tel:<?php echo htmlspecialchars($supplier['phone']); ?>"><?php echo htmlspecialchars($supplier['phone']); ?></a>
                                    <?php else: ?>
                                        <span class="text-muted">Not provided</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <tr>
                                <th>Address:</th>
                                <td>
                                    <?php 
                                    $address = array_filter([
                                        $supplier['address'] ?? '',
                                        $supplier['city'] ?? '',
                                        $supplier['country'] ?? ''
                                    ]);
                                    echo $address ? implode('<br>', array_map('escape_html', $address)) : 'Not provided';
                                    ?>
                                </td>
                            </tr>
                            <tr>
                                <th>Tax ID:</th>
                                <td><?php echo htmlspecialchars($supplier['tax_id'] ?? 'Not provided'); ?></td>
                            </tr>
                            <tr>
                                <th>Payment Terms:</th>
                                <td><?php echo escape_html($supplier['payment_terms'] ?? 'Not specified'); ?></td>
                            </tr>
                            <tr>
                                <th>Status:</th>
                                <td>
                                    <?php if (!empty($supplier['is_active'])): ?>
                                        <span class="badge bg-success">Active</span>
                                    <?php else: ?>
                                        <span class="badge bg-danger">Inactive</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Statistics -->
            <div class="col-md-4">
                <div class="card card-success">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-chart-bar me-1"></i>
                            Purchase Statistics
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-6">
                                <div class="info-box bg-light">
                                    <span class="info-box-icon bg-info elevation-1">
                                        <i class="fas fa-shopping-cart"></i>
                                    </span>
                                    <div class="info-box-content">
                                        <span class="info-box-text">Total POs</span>
                                        <span class="info-box-number"><?php echo $stats['total_pos']; ?></span>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-6">
                                <div class="info-box bg-light">
                                    <span class="info-box-icon bg-warning elevation-1">
                                        <i class="fas fa-clock"></i>
                                    </span>
                                    <div class="info-box-content">
                                        <span class="info-box-text">Pending</span>
                                        <span class="info-box-number"><?php echo $stats['pending_pos']; ?></span>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-6">
                                <div class="info-box bg-light">
                                    <span class="info-box-icon bg-success elevation-1">
                                        <i class="fas fa-dollar-sign"></i>
                                    </span>
                                    <div class="info-box-content">
                                        <span class="info-box-text">Total Spent</span>
                                        <span class="info-box-number"><?php echo format_currency($stats['total_spent']); ?></span>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-6">
                                <div class="info-box bg-light">
                                    <span class="info-box-icon bg-danger elevation-1">
                                        <i class="fas fa-calculator"></i>
                                    </span>
                                    <div class="info-box-content">
                                        <span class="info-box-text">Avg PO Value</span>
                                        <span class="info-box-number"><?php echo format_currency($stats['avg_po_value']); ?></span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <hr>
                        
                        <table class="table table-sm">
                            <tr>
                                <th>First Order:</th>
                                <td class="text-end"><?php echo $stats['first_order'] ? date('M d, Y', strtotime($stats['first_order'])) : 'Never'; ?></td>
                            </tr>
                            <tr>
                                <th>Last Order:</th>
                                <td class="text-end"><?php echo $stats['last_order'] ? date('M d, Y', strtotime($stats['last_order'])) : 'Never'; ?></td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Common Products -->
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-box me-1"></i>
                            Frequently Purchased
                        </h3>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($common_products)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-box-open fa-3x mb-3"></i>
                                <p>No purchase history</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Product</th>
                                            <th class="text-center">Orders</th>
                                            <th class="text-end">Total Qty</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($common_products as $product): ?>
                                        <tr>
                                            <td>
                                                <a href="/HMSPOS/pos/products/view.php?id=<?php echo $product['product_id'] ?? 0; ?>">
                                                    <?php echo escape_html($product['product_name'] ?? ''); ?>
                                                </a>
                                                <br>
                                                <small class="text-muted"><?php echo escape_html($product['product_code'] ?? ''); ?></small>
                                            </td>
                                            <td class="text-center"><?php echo $product['order_count'] ?? 0; ?></td>
                                            <td class="text-end"><?php echo $product['total_ordered'] ?? 0; ?></td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Recent Purchase Orders -->
        <div class="row mt-3">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-clipboard-list me-1"></i>
                            Recent Purchase Orders
                        </h3>
                        <div class="card-tools">
                            <a href="../purchases/index.php?supplier_id=<?php echo $supplier_id; ?>" class="btn btn-sm btn-primary">
                                View All
                            </a>
                        </div>
                    </div>
                    
                    <div class="card-body p-0">
                        <?php if (empty($recent_pos)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-clipboard-list fa-3x mb-3"></i>
                                <p>No purchase orders yet</p>
                                <a href="../purchases/create-po.php?supplier_id=<?php echo $supplier_id; ?>" class="btn btn-primary">
                                    Create First PO
                                </a>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>PO Number</th>
                                            <th>Order Date</th>
                                            <th>Expected Date</th>
                                            <th class="text-center">Items</th>
                                            <th class="text-end">Total</th>
                                            <th>Status</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($recent_pos as $po): ?>
                                        <tr>
                                            <td>
                                                <a href="../purchases/view.php?id=<?php echo $po['po_id'] ?? 0; ?>">
                                                    <?php echo htmlspecialchars($po['po_number'] ?? ''); ?>
                                                </a>
                                            </td>
                                            <td><?php echo isset($po['order_date']) ? date('M d, Y', strtotime($po['order_date'])) : 'N/A'; ?></td>
                                            <td>
                                                <?php if (!empty($po['expected_date'])): ?>
                                                    <?php echo date('M d, Y', strtotime($po['expected_date'])); ?>
                                                    <?php if (strtotime($po['expected_date']) < time() && ($po['status'] ?? '') != 'received'): ?>
                                                        <span class="badge bg-danger">Overdue</span>
                                                    <?php endif; ?>
                                                <?php else: ?>
                                                    <span class="text-muted">-</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-center"><?php echo $po['item_count'] ?? 0; ?></td>
                                            <td class="text-end"><?php echo format_currency($po['total_amount'] ?? 0); ?></td>
                                            <td>
                                                <span class="badge bg-<?php 
                                                    $status = $po['status'] ?? '';
                                                    echo $status == 'received' ? 'success' : 
                                                        ($status == 'partial' ? 'warning' : 
                                                        ($status == 'ordered' ? 'info' : 
                                                        ($status == 'draft' ? 'secondary' : 'danger')));
                                                ?>">
                                                    <?php echo ucfirst($status); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <?php if (($po['status'] ?? '') != 'received'): ?>
                                                    <a href="../purchases/receive.php?id=<?php echo $po['po_id'] ?? 0; ?>" 
                                                       class="btn btn-sm btn-success">
                                                        <i class="fas fa-truck"></i> Receive
                                                    </a>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<style>
.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>';
}
?>