<?php
session_start();
require_once '../config/database.php';
require_once '../includes/auth.php';
require_once '../includes/functions.php';

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

if (!isLoggedIn()) {
    jsonResponse(false, 'Unauthorized');
}

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

switch ($action) {
    case 'save_transaksi':
        saveTransaksi();
        break;
    
    case 'get_transaksi':
        getTransaksi();
        break;
    
    case 'get_transaksi_list':
        getTransaksiList();
        break;
    
    default:
        jsonResponse(false, 'Invalid action');
}

function saveTransaksi() {
    try {
        $items = json_decode($_POST['items'] ?? '[]', true);
        $total = floatval($_POST['total'] ?? 0);
        $user_id = $_SESSION['user_id'];
        $tanggal = date('Y-m-d');
        
        if (empty($items) || $total <= 0) {
            jsonResponse(false, 'Data tidak valid');
        }
        
        $conn = getConnection();
        $conn->begin_transaction();
        
        try {
            // Insert transaksi header
            $sql = "INSERT INTO transaksi (tanggal, total, id_user) VALUES (?, ?, ?)";
            $transaksi_id = insert($sql, [$tanggal, $total, $user_id], 'sdi');
            
            // Insert transaksi details
            $sql_detail = "INSERT INTO transaksi_detail (id_transaksi, id_layanan, nama_layanan, quantity, harga, subtotal) 
                          VALUES (?, ?, ?, ?, ?, ?)";
            
            foreach ($items as $item) {
                $stmt = $conn->prepare($sql_detail);
                $stmt->bind_param('iisidd', 
                    $transaksi_id,
                    $item['id_layanan'],
                    $item['nama_layanan'],
                    $item['quantity'],
                    $item['harga'],
                    $item['subtotal']
                );
                $stmt->execute();
                $stmt->close();
            }
            
            $conn->commit();
            
            jsonResponse(true, 'Transaksi berhasil disimpan', ['id' => $transaksi_id]);
        } catch (Exception $e) {
            $conn->rollback();
            throw $e;
        }
        
    } catch (Exception $e) {
        jsonResponse(false, $e->getMessage());
    }
}

function getTransaksi() {
    try {
        $id = intval($_GET['id'] ?? 0);
        
        if ($id <= 0) {
            jsonResponse(false, 'ID tidak valid');
        }
        
        // Get transaksi header
        $sql = "SELECT t.*, u.nama as kasir 
                FROM transaksi t 
                JOIN users u ON t.id_user = u.id 
                WHERE t.id = ?";
        $result = query($sql, [$id], 'i');
        
        if ($result->num_rows === 0) {
            jsonResponse(false, 'Transaksi tidak ditemukan');
        }
        
        $transaksi = $result->fetch_assoc();
        
        // Get transaksi details
        $sql_detail = "SELECT * FROM transaksi_detail WHERE id_transaksi = ?";
        $result_detail = query($sql_detail, [$id], 'i');
        
        $details = [];
        while ($row = $result_detail->fetch_assoc()) {
            $details[] = $row;
        }
        
        $transaksi['details'] = $details;
        
        jsonResponse(true, 'Success', $transaksi);
        
    } catch (Exception $e) {
        jsonResponse(false, $e->getMessage());
    }
}

function getTransaksiList() {
    try {
        $dari = clean($_GET['dari'] ?? '');
        $sampai = clean($_GET['sampai'] ?? '');
        $search = clean($_GET['search'] ?? '');
        
        $sql = "SELECT t.id, t.tanggal, t.total, t.created_at, u.nama as kasir
                FROM transaksi t
                JOIN users u ON t.id_user = u.id
                WHERE 1=1";
        
        $params = [];
        $types = '';
        
        if (!empty($dari)) {
            $sql .= " AND DATE(t.created_at) >= ?";
            $params[] = $dari;
            $types .= 's';
        }
        
        if (!empty($sampai)) {
            $sql .= " AND DATE(t.created_at) <= ?";
            $params[] = $sampai;
            $types .= 's';
        }
        
        if (!empty($search)) {
            $sql .= " AND (t.id LIKE ? OR u.nama LIKE ?)";
            $searchTerm = "%$search%";
            $params[] = $searchTerm;
            $params[] = $searchTerm;
            $types .= 'ss';
        }
        
        $sql .= " ORDER BY t.created_at DESC";
        
        $result = query($sql, $params, $types);
        $transaksi = [];
        while ($row = $result->fetch_assoc()) {
            $transaksi[] = $row;
        }
        
        jsonResponse(true, 'Success', $transaksi);
    } catch (Exception $e) {
        jsonResponse(false, $e->getMessage());
    }
}
?>
