<?php
session_start();
require_once 'shikanisha.kts.php';

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

// Check if user is logged in
if (!isset($_SESSION['user_id']) || !isset($_SESSION['type']) || !in_array($_SESSION['type'], ['Cashier', 'Manager', 'Waiter'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

// Error reporting should be configured in php.ini for production
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(0);

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

try {
    switch ($action) {
        case 'get_employees':
            getEmployees();
            break;
        case 'get_current_shift':
            getCurrentShift();
            break;
        case 'get_all_shifts':
            getAllShifts();
            break;
        case 'start_shift':
            startShift();
            break;
        case 'get_shift_data':
            echo json_encode(getShiftData());
            break;
        case 'close_shift':
            closeShift();
            break;
        case 'record_payment':
            recordPayment();
            break;
        case 'get_shift_report':
            getShiftReport();
            break;
        case 'get_last_shift':
            getLastShift();
            break;
        case 'get_active_shifts':
            getActiveShifts();
            break;
        case 'get_active_shifts_full_report':
            echo json_encode(getActiveShiftsReport());
            break;
        case 'get_shift_history':
            getShiftHistory();
            break;
        case 'get_cash_summary':
            getCashSummary();
            break;
        case 'get_active_shifts_summary':
            echo json_encode(getActiveShiftsSummary());
            break;
        default:
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
            break;
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Server error: ' . $e->getMessage()]);
}


function getEmployees() {
    global $conn;
    
    $query = "SELECT employee_id, name, username, role_id, is_active FROM employees WHERE is_active = 1 ORDER BY name";
    $result = $conn->query($query);
    
    $employees = [];
    while ($row = $result->fetch_assoc()) {
        $employees[] = $row;
    }
    
    echo json_encode(['success' => true, 'data' => $employees]);
}

function getCurrentShift() {
    global $conn;
    
    $employeeId = $_SESSION['user_id'];
    $query = "SELECT * FROM shifts WHERE employee_id = ? AND status = 'active' ORDER BY start_time DESC LIMIT 1";
    
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $employeeId);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $shift = $result->fetch_assoc();
        
        // Get employee name
        $employee = $conn->query("SELECT name FROM employees WHERE employee_id = {$shift['employee_id']}")->fetch_assoc();
        $shift['employee_name'] = $employee['name'] ?? 'Unknown';
        
        echo json_encode(['success' => true, 'data' => $shift]);
    } else {
        echo json_encode(['success' => true, 'data' => null]);
    }
}

function getAllShifts() {
    global $conn;
    
    $query = "SELECT s.*, e.name as employee_name 
              FROM shifts s
              JOIN employees e ON s.employee_id = e.employee_id
              WHERE s.status = 'active'";
    $result = $conn->query($query);
    
    $shifts = [];
    while ($row = $result->fetch_assoc()) {
        $shifts[] = $row;
    }
    
    echo json_encode(['success' => true, 'data' => $shifts]);
}

function startShift() {
    global $conn;
    
    $employeeId = intval($_POST['employee_id']);
    $startingCash = floatval($_POST['starting_cash']);
    $notes = $conn->real_escape_string($_POST['notes'] ?? '');
 
    
    // Check if this employee already has an active shift
    $checkQuery = "SELECT * FROM shifts WHERE status = 'active' AND employee_id = ?";
    $checkStmt = $conn->prepare($checkQuery);
    $checkStmt->bind_param("i", $employeeId);
    $checkStmt->execute();
    $checkResult = $checkStmt->get_result();
    
    if ($checkResult->num_rows > 0) {
        echo json_encode(['success' => false, 'message' => 'You already have an active shift']);
        return;
    }
    
    // Insert new shift with prepared statement
    $insertQuery = "INSERT INTO shifts (employee_id, start_time, starting_cash, notes, status) 
                   VALUES (?, NOW(), ?, ?, 'active')";
    $insertStmt = $conn->prepare($insertQuery);
    $insertStmt->bind_param("ids", $employeeId, $startingCash, $notes);
    
    if ($insertStmt->execute()) {
        $shiftId = $conn->insert_id;
        
        // Get the newly created shift
        $getShiftQuery = "SELECT s.*, e.name as employee_name 
                         FROM shifts s
                         JOIN employees e ON s.employee_id = e.employee_id
                         WHERE s.shift_id = ?";
        $getStmt = $conn->prepare($getShiftQuery);
        $getStmt->bind_param("i", $shiftId);
        $getStmt->execute();
        $shift = $getStmt->get_result()->fetch_assoc();
        
        echo json_encode([
            'success' => true, 
            'message' => 'Shift started successfully', 
            'data' => $shift
        ]);
    } else {
        echo json_encode([
            'success' => false, 
            'message' => 'Failed to start shift: ' . $conn->error
        ]);
    }
}

function closeShift() {
    global $conn;
    
    try {
        // Begin transaction
        $conn->begin_transaction();
        
        // Close all active shifts
        $updateQuery = "UPDATE shifts SET 
                        end_time = NOW(),
                        status = 'closed',
                        notes = CONCAT(IFNULL(notes, ''), '\nClosed by cashier at ', NOW())
                        WHERE status = 'active'";
        
        $stmt = $conn->prepare($updateQuery);
        
        if (!$stmt->execute()) {
            throw new Exception('Failed to close shifts: ' . $conn->error);
        }
        
        $closedCount = $stmt->affected_rows;
        
        // Commit transaction
        $conn->commit();
        
        echo json_encode([
            'success' => true,
            'message' => "Successfully closed $closedCount active shifts",
            'closed_count' => $closedCount
        ]);
        
    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode([
            'success' => false,
            'message' => 'Error: ' . $e->getMessage()
        ]);
    }
}
function getActiveShifts() {
    global $conn;
    
    $query = "SELECT s.*, e.name as employee_name 
              FROM shifts s
              JOIN employees e ON s.employee_id = e.employee_id
              WHERE s.status = 'active'
              ORDER BY s.start_time DESC";
    
    $result = $conn->query($query);
    
    $shifts = [];
    while ($row = $result->fetch_assoc()) {
        $shifts[] = $row;
    }
    
    echo json_encode(['success' => true, 'data' => $shifts]);
}

function getActiveShiftsReport() {
    global $conn;

    // Get all transactions from active shifts
    $query = "SELECT tr.* 
              FROM transaction_receipts tr
              JOIN shifts s ON tr.shift_id = s.shift_id
              WHERE s.status = 'active'";
    $transactions = [];
    $result = $conn->query($query);

    if (!$result) {
        return ['success' => false, 'message' => 'Database error: ' . $conn->error];
    }

    $transIds = [];
    while ($row = $result->fetch_assoc()) {
        $transactions[$row['trans_id']] = $row;
        $transIds[] = $row['trans_id'];
    }

    // Get all expenses from active shifts
    $expenses = [];
    $expensesQuery = $conn->query("
        SELECT expense_name, expense_amount, date_incurred
        FROM expenses
        WHERE shift_id IN (SELECT shift_id FROM shifts WHERE status = 'active')
    ");

    if ($expensesQuery) {
        while ($expense = $expensesQuery->fetch_assoc()) {
            $expenses[] = [
                'name' => $expense['expense_name'],
                'amount' => (float)$expense['expense_amount'],
                'date' => $expense['date_incurred']
            ];
        }
    }

    if (empty($transIds) && empty($expenses)) {
        return ['success' => false, 'message' => 'No transactions or expenses found for active shifts'];
    }

    $transIdsStr = empty($transIds) ? "''" : implode(',', $transIds);

    // Get all products and aggregate quantities and amounts
    $products = [];
    if (!empty($transIdsStr)) {
        $productsQuery = $conn->query("
            SELECT product_name, 
                   SUM(quantity) AS total_quantity, 
                   SUM(quantity * selling_price) AS total_amount
            FROM sales
            WHERE trans_id IN ($transIdsStr)
            GROUP BY product_name
        ");

        if ($productsQuery) {
            while ($product = $productsQuery->fetch_assoc()) {
                $products[] = [
                    'name' => $product['product_name'],
                    'quantity' => (float)$product['total_quantity'],
                    'total' => (float)$product['total_amount']
                ];
            }
        }
    }

    // Get all payments and aggregate by method
    $payments = [];
    $totalCashReceived = 0; // Initialize variable for cash payments only
    if (!empty($transIdsStr)) {
        $paymentsQuery = $conn->query("
            SELECT payment_method, SUM(amount) AS total_amount
            FROM payments
            WHERE trans_id IN ($transIdsStr)
            GROUP BY payment_method
        ");

        if ($paymentsQuery) {
            while ($payment = $paymentsQuery->fetch_assoc()) {
                $payments[] = [
                    'method' => $payment['payment_method'],
                    'amount' => (float)$payment['total_amount']
                ];
                
                // Sum only cash payments
                if (strtolower($payment['payment_method']) === 'cash') {
                    $totalCashReceived += (float)$payment['total_amount'];
                }
            }
        }
    }

    // Calculate totals
    $totalSales = 0;
    $totalReceived = 0;
    $totalExpenses = 0;

    foreach ($transactions as $trans) {
        $totalSales += (float)$trans['total'];
        $totalReceived += (float)$trans['amount_received'];
    }

    foreach ($expenses as $expense) {
        $totalExpenses += (float)$expense['amount'];
    }

    $totalDebt = $totalSales - $totalReceived;
    $cashAtHand = $totalCashReceived - $totalExpenses; // Now using only cash payments

    return [
        'success' => true,
        'data' => [
            'total_sales' => round($totalSales, 2),
            'total_received' => round($totalReceived, 2),
            'total_debt' => round($totalDebt, 2),
            'total_expenses' => round($totalExpenses, 2),
            'cash_at_hand' => round($cashAtHand, 2),
            'products' => $products,
            'payments' => $payments,
            'expenses' => $expenses,
            'generated_at' => date('Y-m-d H:i:s')
        ]
    ];
}
function getShiftReport() {
    global $conn;
    
    $shiftId = intval($_GET['shift_id']);
    
    // Get shift data with employee name
    $shiftQuery = $conn->prepare("
        SELECT s.*, e.name as employee_name 
        FROM shifts s
        JOIN employees e ON s.employee_id = e.employee_id
        WHERE s.shift_id = ?
    ");
    
    if (!$shiftQuery) {
        echo json_encode(['success' => false, 'message' => 'Database error: ' . $conn->error]);
        return;
    }
    
    $shiftQuery->bind_param("i", $shiftId);
    $shiftQuery->execute();
    $shiftResult = $shiftQuery->get_result();
    $shift = $shiftResult->fetch_assoc();
    
    if (!$shift) {
        echo json_encode(['success' => false, 'message' => 'Shift not found']);
        return;
    }
    
    // Get all transactions for this shift
    $transactions = [];
    $transQuery = $conn->prepare("
        SELECT trans_id, amount_received, total, phone_number, seller_date AS created_at 
        FROM transaction_receipts 
        WHERE shift_id = ?
    ");
    
    if (!$transQuery) {
        echo json_encode(['success' => false, 'message' => 'Database error: ' . $conn->error]);
        return;
    }
    
    $transQuery->bind_param("i", $shiftId);
    $transQuery->execute();
    $transResult = $transQuery->get_result();
    
    while ($trans = $transResult->fetch_assoc()) {
        $transId = $trans['trans_id'];
        
        // Get sales items for each transaction
        $salesItems = [];
        $salesQuery = $conn->prepare("
            SELECT product_name, quantity, selling_price 
            FROM sales 
            WHERE trans_id = ?
        ");
        
        if ($salesQuery) {
            $salesQuery->bind_param("s", $transId);
            $salesQuery->execute();
            $salesResult = $salesQuery->get_result();
            
            while ($sale = $salesResult->fetch_assoc()) {
                $sale['subtotal'] = $sale['quantity'] * $sale['selling_price'];
                $salesItems[] = $sale;
            }
        }
        $trans['items'] = $salesItems;
        
        // Get payments for each transaction
        $payments = [];
        $paymentQuery = $conn->prepare("
            SELECT payment_method, amount 
            FROM payments 
            WHERE trans_id = ?
        ");
        
        if ($paymentQuery) {
            $paymentQuery->bind_param("s", $transId);
            $paymentQuery->execute();
            $paymentResult = $paymentQuery->get_result();
            
            while ($payment = $paymentResult->fetch_assoc()) {
                $payments[] = $payment;
            }
        }
        $trans['payments'] = $payments;
        
        $transactions[] = $trans;
    }
    
    // Calculate summary data
    $totalSales = array_sum(array_column($transactions, 'total'));
    $totalReceived = array_sum(array_column($transactions, 'amount_received'));
    $totalDebt = $totalSales - $totalReceived;
    
    // Calculate payment method totals
    $paymentMethodTotals = [];
    foreach ($transactions as $trans) {
        foreach ($trans['payments'] as $payment) {
            $method = $payment['payment_method'];
            if (!isset($paymentMethodTotals[$method])) {
                $paymentMethodTotals[$method] = 0;
            }
            $paymentMethodTotals[$method] += $payment['amount'];
        }
    }
    
    // Prepare response
    $response = [
        'success' => true,
        'data' => [
            'shift' => $shift,
            'transactions' => $transactions,
            'summary' => [
                'total_sales' => $totalSales,
                'total_received' => $totalReceived,
                'total_debt' => $totalDebt,
                'payment_method_totals' => $paymentMethodTotals
            ]
        ]
    ];
    
    echo json_encode($response);
}
function getLastShift() {
    global $conn;
    
    $employeeId = $_SESSION['user_id'];
    $query = "SELECT * FROM shifts 
              WHERE employee_id = ? AND status = 'closed' 
              ORDER BY end_time DESC LIMIT 1";
    
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $employeeId);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $shift = $result->fetch_assoc();
        
        // Get employee name
        $employee = $conn->query("SELECT name FROM employees WHERE employee_id = {$shift['employee_id']}")->fetch_assoc();
        $shift['employee_name'] = $employee['name'] ?? 'Unknown';
        
        echo json_encode(['success' => true, 'data' => $shift]);
    } else {
        echo json_encode(['success' => true, 'data' => null]);
    }
}

function getShiftHistory() {
    global $conn;
    
    $employeeId = $_SESSION['user_id'];
    $page = intval($_GET['page'] ?? 1);
    $limit = 10;
    $offset = ($page - 1) * $limit;
    $dateFilter = $_GET['date'] ?? '';
    
    $where = "WHERE s.employee_id = ?";
    if ($dateFilter) {
        $where .= " AND DATE(s.start_time) = ?";
    }
    
    // Get shifts
    $query = "SELECT s.*, e.name as employee_name 
              FROM shifts s
              JOIN employees e ON s.employee_id = e.employee_id
              $where
              ORDER BY start_time DESC
              LIMIT ? OFFSET ?";
    
    $stmt = $conn->prepare($query);
    
    if ($dateFilter) {
        $stmt->bind_param("isii", $employeeId, $dateFilter, $limit, $offset);
    } else {
        $stmt->bind_param("iii", $employeeId, $limit, $offset);
    }
    
    $stmt->execute();
    $shifts = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    
    // Get total count for pagination
    $countQuery = "SELECT COUNT(*) as total FROM shifts $where";
    $countStmt = $conn->prepare($countQuery);
    
    if ($dateFilter) {
        $countStmt->bind_param("is", $employeeId, $dateFilter);
    } else {
        $countStmt->bind_param("i", $employeeId);
    }
    
    $countStmt->execute();
    $total = $countStmt->get_result()->fetch_assoc()['total'];
    $totalPages = ceil($total / $limit);
    
    echo json_encode([
        'success' => true,
        'data' => [
            'shifts' => $shifts,
            'total_pages' => $totalPages
        ]
    ]);
}
function getCashSummary() {
    global $conn;
    
    try {
        // Get cash summary for active shifts
        $query = "SELECT 
                    SUM(s.starting_cash) as total_opening_cash,
                    SUM(s.ending_cash) as total_current_cash,
                    SUM(CASE WHEN p.payment_method = 'cash' THEN p.amount ELSE 0 END) as total_cash_payments,
                    COUNT(DISTINCT s.shift_id) as active_shifts_count,
                    GROUP_CONCAT(DISTINCT s.shift_id) as shift_ids
                  FROM shifts s
                  LEFT JOIN transaction_receipts tr ON s.shift_id = tr.shift_id
                  LEFT JOIN payments p ON tr.trans_id = p.trans_id
                  WHERE s.status = 'active'";
        
        $result = $conn->query($query);
        
        if (!$result) {
            throw new Exception("Database query failed: " . $conn->error);
        }
        
        $data = $result->fetch_assoc();
        
        // Get total expenses for these shifts
        $expenseQuery = "SELECT SUM(expense_amount) as total_expenses 
                         FROM expenses 
                         WHERE shift_id IN (" . $data['shift_ids'] . ")";
        
        $expenseResult = $conn->query($expenseQuery);
        $expenses = $expenseResult->fetch_assoc();
        $total_expenses = $expenses['total_expenses'] ?? 0;
        
        // Calculate expected cash (opening + payments - expenses)
        $data['total_expected_cash'] = $data['total_opening_cash'] + $data['total_cash_payments'] - $total_expenses;
        
        // Calculate cash difference (current - expected)
        $data['cash_difference'] = $data['total_current_cash'] - $data['total_expected_cash'];
        $data['total_expenses'] = $total_expenses;
        
        echo json_encode([
            'success' => true,
            'message' => 'Cash summary retrieved successfully',
            'data' => $data
        ]);
        
    } catch (Exception $e) {
        echo json_encode([
            'success' => false,
            'message' => 'Error retrieving cash summary: ' . $e->getMessage()
        ]);
    }
}
function getShiftData() {
    global $conn;
    
    try {
        // Get all shift data
        $query = "SELECT s.`shift_id`, s.`employee_id`, e.`name` as employee_name,
                 s.`total_orders` as total_sales, 
                 s.`total_payments` as total_payments, 
                 s.`total_debt` as total_debt,
                 s.`status`,
                 s.`start_time`,
                 IFNULL(s.`end_time`, 'Active') as end_time
                 FROM `shifts` s
                 LEFT JOIN `employees` e ON s.employee_id = e.employee_id
                 ORDER BY s.status DESC, s.start_time DESC";
        
        $result = $conn->query($query);
        
        if (!$result) {
            throw new Exception("Database query failed: " . $conn->error);
        }
        
        $data = [];
        while ($row = $result->fetch_assoc()) {
            $data[] = $row;
        }
        
        // Get sums for active shifts only
        $sumQuery = "SELECT 
                    COUNT(*) as active_shifts,
                    SUM(total_orders) as total_sales,
                    SUM(total_payments) as total_payments,
                    SUM(total_debt) as total_debt
                    FROM `shifts`
                    WHERE status = 'active'";
        
        $sumResult = $conn->query($sumQuery);
        $sums = $sumResult->fetch_assoc();
        
        return [
            'success' => true,
            'data' => $data,
            'sums' => $sums
        ];
        
    } catch (Exception $e) {
        return [
            'success' => false,
            'message' => 'Error: ' . $e->getMessage()
        ];
    }
}

function getActiveShiftsSummary() {
    global $conn;
    
    try {
        $query = "SELECT 
                    COUNT(*) as active_shifts,
                    SUM(total_orders) as total_sales,
                    SUM(total_payments) as total_payments,
                    SUM(total_debt) as total_debt
                  FROM `shifts`
                  WHERE status = 'active'";
        
        $result = $conn->query($query);
        
        if (!$result) {
            throw new Exception("Database query failed: " . $conn->error);
        }
        
        $data = $result->fetch_assoc();
        
        return [
            'success' => true,
            'data' => $data
        ];
        
    } catch (Exception $e) {
        return [
            'success' => false,
            'message' => 'Error: ' . $e->getMessage()
        ];
    }
}


?>