<?php
session_start();
require_once 'db.php';

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

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

$action = $_GET['action'] ?? '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'request') {
    $data = json_decode(file_get_contents("php://input"), true);
    
    $sale_id = $data['sale_id'] ?? null;
    $passed_shift_id = $data['shift_id'] ?? null;
    $items = $data['items'] ?? [];
    $reason = $data['reason'] ?? '';

    if (!$sale_id || empty($items)) {
        echo json_encode(['success' => false, 'message' => 'Invalid request data']);
        exit;
    }

    try {
        $pdo->beginTransaction();

        // Get sale info
        $stmt = $pdo->prepare("SELECT customer_id FROM sales WHERE id = ?");
        $stmt->execute([$sale_id]);
        $sale = $stmt->fetch();

        if (!$sale) {
            throw new Exception("Sale not found");
        }

        // Calculate total refund
        $total_refunded = 0;
        foreach ($items as $item) {
            $total_refunded += $item['refund_amount'];
        }

        // Determine shift_id: Use passed ID if valid, otherwise fallback to session check
        $shift_id = $passed_shift_id;
        if (!$shift_id) {
            $shiftStmt = $pdo->prepare("SELECT id FROM shifts WHERE user_id = ? AND status = 'Open' ORDER BY id DESC LIMIT 1");
            $shiftStmt->execute([$_SESSION['user_id']]);
            $activeShift = $shiftStmt->fetch();
            $shift_id = $activeShift ? $activeShift['id'] : null;
        }

        // Insert Credit Note
        // If requester is Admin, auto-approve
        $status = ($_SESSION['role'] === 'Admin') ? 'Approved' : 'Pending';
        $approval_user = ($_SESSION['role'] === 'Admin') ? $_SESSION['user_id'] : null;
        $approved_at = ($_SESSION['role'] === 'Admin') ? date('Y-m-d H:i:s') : null;

        $stmt = $pdo->prepare("INSERT INTO credit_notes (sale_id, user_id, shift_id, customer_id, total_refunded, reason, status, approval_user_id, approved_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$sale_id, $_SESSION['user_id'], $shift_id, $sale['customer_id'], $total_refunded, $reason, $status, $approval_user, $approved_at]);
        $cn_id = $pdo->lastInsertId();

        // Insert Items
        $itemStmt = $pdo->prepare("INSERT INTO credit_note_items (credit_note_id, sale_item_id, product_id, quantity_refunded, refund_amount) VALUES (?, ?, ?, ?, ?)");
        foreach ($items as $item) {
            $itemStmt->execute([$cn_id, $item['sale_item_id'], $item['product_id'], $item['quantity'], $item['refund_amount']]);
            
            // If auto-approved, update stock immediately
            if ($status === 'Approved') {
                $updateStock = $pdo->prepare("UPDATE products SET stock_quantity = stock_quantity + ? WHERE id = ?");
                $updateStock->execute([$item['quantity'], $item['product_id']]);
            }
        }

        $pdo->commit();
        $msg = ($status === 'Approved') ? 'Credit note processed and stock updated' : 'Credit note request submitted to admin';
        echo json_encode(['success' => true, 'message' => $msg]);
    } catch (Exception $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }

} elseif ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'approve') {
    // Only Admin can approve
    if ($_SESSION['role'] !== 'Admin') {
        echo json_encode(['success' => false, 'message' => 'Unauthorized: Admin access required']);
        exit;
    }

    $data = json_decode(file_get_contents("php://input"), true);
    $cn_id = $data['id'] ?? null;

    if (!$cn_id) {
        echo json_encode(['success' => false, 'message' => 'Credit Note ID required']);
        exit;
    }

    try {
        $pdo->beginTransaction();

        // Get CN info
        $stmt = $pdo->prepare("SELECT * FROM credit_notes WHERE id = ? AND status = 'Pending'");
        $stmt->execute([$cn_id]);
        $cn = $stmt->fetch();

        if (!$cn) {
            throw new Exception("Credit note not found or already processed");
        }

        // Update status and ensure shift_id is set if it was missing
        $stmt = $pdo->prepare("UPDATE credit_notes SET status = 'Approved', approval_user_id = ?, approved_at = NOW(), 
                               shift_id = COALESCE(shift_id, (SELECT id FROM shifts WHERE user_id = credit_notes.user_id AND status = 'Open' ORDER BY id DESC LIMIT 1))
                               WHERE id = ?");
        $stmt->execute([$_SESSION['user_id'], $cn_id]);

        // Restore stock
        $itemsStmt = $pdo->prepare("SELECT * FROM credit_note_items WHERE credit_note_id = ?");
        $itemsStmt->execute([$cn_id]);
        $items = $itemsStmt->fetchAll();

        foreach ($items as $item) {
            $updateStock = $pdo->prepare("UPDATE products SET stock_quantity = stock_quantity + ? WHERE id = ?");
            $updateStock->execute([$item['quantity_refunded'], $item['product_id']]);
        }

        $pdo->commit();
        echo json_encode(['success' => true, 'message' => 'Credit note approved and stock restored']);
    } catch (Exception $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }

} elseif ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'reject') {
    // Only Admin can reject
    if ($_SESSION['role'] !== 'Admin') {
        echo json_encode(['success' => false, 'message' => 'Unauthorized: Admin access required']);
        exit;
    }

    $data = json_decode(file_get_contents("php://input"), true);
    $cn_id = $data['id'] ?? null;

    if (!$cn_id) {
        echo json_encode(['success' => false, 'message' => 'Credit Note ID required']);
        exit;
    }

    try {
        // Check if still pending
        $stmt = $pdo->prepare("SELECT status FROM credit_notes WHERE id = ?");
        $stmt->execute([$cn_id]);
        $cn = $stmt->fetch();
        if (!$cn || $cn['status'] !== 'Pending') {
             throw new Exception("Credit note not found or already processed");
        }

        $stmt = $pdo->prepare("UPDATE credit_notes SET status = 'Rejected', approval_user_id = ?, approved_at = NOW() WHERE id = ?");
        $stmt->execute([$_SESSION['user_id'], $cn_id]);
        echo json_encode(['success' => true, 'message' => 'Credit note request rejected']);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }

} elseif ($_SERVER['REQUEST_METHOD'] === 'GET' && $action === 'get_items') {
    $cn_id = $_GET['id'] ?? null;
    if (!$cn_id) {
        echo json_encode(['success' => false, 'message' => 'ID required']);
        exit;
    }

    $stmt = $pdo->prepare("SELECT cni.*, p.name FROM credit_note_items cni 
                           JOIN products p ON cni.product_id = p.id 
                           WHERE cni.credit_note_id = ?");
    $stmt->execute([$cn_id]);
    $items = $stmt->fetchAll();

    // Also get CN metadata
    $stmt = $pdo->prepare("SELECT cn.*, u.username as requester, a.username as approver 
                           FROM credit_notes cn 
                           JOIN users u ON cn.user_id = u.id 
                           LEFT JOIN users a ON cn.approval_user_id = a.id 
                           WHERE cn.id = ?");
    $stmt->execute([$cn_id]);
    $meta = $stmt->fetch();

    echo json_encode(['success' => true, 'data' => $items, 'meta' => $meta]);

} elseif ($_SERVER['REQUEST_METHOD'] === 'GET' && $action === 'list_pending') {
    // Return all status so we can see what happened recently
    $stmt = $pdo->query("SELECT cn.*, u.username as requester, s.sale_date, c.name as customer_name 
                         FROM credit_notes cn 
                         JOIN users u ON cn.user_id = u.id 
                         JOIN sales s ON cn.sale_id = s.id 
                         LEFT JOIN customers c ON cn.customer_id = c.id 
                         ORDER BY cn.created_at DESC LIMIT 100");
    echo json_encode(['success' => true, 'data' => $stmt->fetchAll()]);

} else {
    echo json_encode(['success' => false, 'message' => 'Unknown action']);
}
