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

header('Content-Type: application/json');

if (!isset($_SESSION['user'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid purchase ID']);
    exit;
}

$purchase_id = intval($_GET['id']);
$user = $_SESSION['user'];
$user_role = $user['role'] ?? 'cashier';
$user_shop_id = $user['shop_id'] ?? 0;

try {
    // Get purchase details
    $sql = "SELECT p.*, s.name as supplier_name, s.contact as supplier_contact, 
                   u.fullname as created_by_name, sh.name as shop_name
            FROM purchases p
            LEFT JOIN suppliers s ON p.supplier_id = s.id
            LEFT JOIN users u ON p.created_by = u.id
            LEFT JOIN shops sh ON p.shop_id = sh.id
            WHERE p.id = ?";
    
    $params = [$purchase_id];
    
    // Add shop restriction for non-admin users
    if ($user_role !== 'admin' && $user_shop_id > 0) {
        $sql .= " AND p.shop_id = ?";
        $params[] = $user_shop_id;
    }
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $purchase = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$purchase) {
        echo json_encode(['success' => false, 'message' => 'Purchase not found or access denied']);
        exit;
    }
    
    // Get purchase items
    $sql = "SELECT pl.*, pb.batch_no, p.name as product_name, p.sku as product_sku
            FROM purchase_lines pl
            LEFT JOIN product_batches pb ON pl.batch_id = pb.id
            LEFT JOIN products p ON pb.product_id = p.id
            WHERE pl.purchase_id = ?
            ORDER BY pl.id";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$purchase_id]);
    $items = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Calculate line totals and items count
    $items_count = 0;
    $total_qty = 0;
    $total_cost = 0;
    
    foreach ($items as &$item) {
        $item['line_total'] = $item['qty'] * $item['cost_price'];
        $items_count++;
        $total_qty += $item['qty'];
        $total_cost += $item['line_total'];
    }
    
    // Format response data
    $response = [
        'success' => true,
        'purchase' => [
            'id' => $purchase['id'],
            'invoice_no' => $purchase['invoice_no'],
            'purchase_date' => $purchase['purchase_date'],
            'purchase_date_formatted' => date('d-M-Y', strtotime($purchase['purchase_date'])),
            'supplier_name' => $purchase['supplier_name'],
            'supplier_contact' => $purchase['supplier_contact'],
            'created_by_name' => $purchase['created_by_name'],
            'shop_name' => $purchase['shop_name'],
            'total' => $purchase['total'],
            'items_count' => $items_count,
            'avg_cost' => $items_count > 0 ? $total_cost / $items_count : 0,
            'items' => $items,
            'notes' => $purchase['notes'] ?? null
        ]
    ];
    
    echo json_encode($response);
    
} catch (Exception $e) {
    error_log("Error fetching purchase details: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Server error: ' . $e->getMessage()]);
}