<?php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Database Connection to XAMPP 'aluaa'
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = 'aluaa';

$conn = new mysqli($db_host, $db_user, $db_pass, $db_name);
if ($conn->connect_error) {
    echo json_encode([
        'status' => 'error',
        'message' => 'فشل الاتصال بقاعدة بيانات aluaa: ' . $conn->connect_error
    ]);
    exit;
}
$conn->set_charset('utf8mb4');
require_once __DIR__ . '/../includes/db.php';

$raw_input = file_get_contents('php://input');
$json_data = !empty($raw_input) ? json_decode($raw_input, true) : [];

$action = isset($_GET['action']) ? $_GET['action'] : (isset($_POST['action']) ? $_POST['action'] : (isset($json_data['action']) ? $json_data['action'] : ''));

if (empty($action) && ($_SERVER['REQUEST_METHOD'] === 'POST' || !empty($json_data['customer_name']))) {
    $action = 'save_order';
}

// Helper function to calculate active shift and fetch company info & logo dynamically from system_settings
function getActiveShiftTimes() {
    global $conn;
    date_default_timezone_set('Asia/Baghdad');

    $settings_res = $conn->query("SELECT org_name, workday_start_hour, workday_end_hour, header_banner FROM system_settings WHERE id = 1");
    $start_hour = 17;
    $end_hour = 17;
    $org_name = 'مكتب الحاج أمجد سهل عبدالامير';
    $logo_url = 'uploads/header_banner_1784917543.png';

    if ($settings_res && $row = $settings_res->fetch_assoc()) {
        $start_hour = intval($row['workday_start_hour']);
        $end_hour = intval($row['workday_end_hour']);
        if (!empty($row['org_name'])) {
            $org_name = $row['org_name'];
        }
        if (!empty($row['header_banner'])) {
            $logo_url = $row['header_banner'];
        }
    }

    $now = new DateTime();
    $current_hour = (int)$now->format('H');

    if ($current_hour >= $start_hour) {
        $start = clone $now;
        $start->setTime($start_hour, 0, 0);
        $end = clone $now;
        $end->modify('+1 day');
        $end->setTime($end_hour, 0, 0);
    } else {
        $start = clone $now;
        $start->modify('-1 day');
        $start->setTime($start_hour, 0, 0);
        $end = clone $now;
        $end->setTime($start_hour, 0, 0);
    }

    $start_formatted = date('h:i a', strtotime($start->format('Y-m-d H:i:s')));
    $start_formatted = str_replace(['AM', 'PM', 'am', 'pm'], ['ص', 'م', 'ص', 'م'], $start_formatted);
    
    $end_formatted = date('h:i a', strtotime($end->format('Y-m-d H:i:s')));
    $end_formatted = str_replace(['AM', 'PM', 'am', 'pm'], ['ص', 'م', 'ص', 'م'], $end_formatted);

    return [
        'org_name' => $org_name,
        'logo_url' => $logo_url,
        'start_hour' => $start_hour,
        'end_hour' => $end_hour,
        'start_str' => $start->format('Y-m-d H:i:s'),
        'end_str' => $end->format('Y-m-d H:i:s'),
        'shift_text' => "الوردية النشطة: $start_formatted إلى $end_formatted"
    ];
}

// 0. GET COMPANY INFO AND SHIFT INFO DYNAMICALLY FROM DATABASE
if ($action === 'get_company_info' || $action === 'get_shift_info') {
    $shift = getActiveShiftTimes();
    echo json_encode([
        'status' => 'success',
        'org_name' => $shift['org_name'],
        'company_name' => $shift['org_name'],
        'logo_url' => $shift['logo_url'],
        'shift' => $shift
    ]);
    exit;
}

// 1. GET MATERIALS STRICTLY FOR ACTIVE SHIFT FROM DATABASE
if ($action === 'get_materials') {
    $shift = getActiveShiftTimes();
    $start_str = $shift['start_str'];
    $end_str = $shift['end_str'];

    $stmt = $conn->prepare("
        SELECT DISTINCT m.id, m.name, COALESCE(g.name, 'غير محدد') AS jallab_name, COALESCE(m.accounting_type, 'وزن * سعر') AS accounting_type
        FROM materials m
        LEFT JOIN gatherers g ON m.jallab_id = g.id
        WHERE m.created_at >= ? AND m.created_at < ?
        ORDER BY m.name ASC
    ");
    $stmt->bind_param("ss", $start_str, $end_str);
    $stmt->execute();
    $res = $stmt->get_result();

    $materials = [];
    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $materials[] = [
                'id' => (int)$row['id'],
                'name' => $row['name'],
                'jallab' => $row['jallab_name'],
                'accounting_type' => $row['accounting_type']
            ];
        }
    }
    $stmt->close();

    echo json_encode([
        'status' => 'success',
        'org_name' => $shift['org_name'],
        'company_name' => $shift['org_name'],
        'logo_url' => $shift['logo_url'],
        'shift_text' => $shift['shift_text'],
        'shift_start' => $start_str,
        'shift_end' => $end_str,
        'materials' => $materials
    ]);
    exit;
}

// 2. GET CUSTOMERS
if ($action === 'get_customers') {
    $res = $conn->query("SELECT id, name, phone FROM customers WHERE status = 'active' OR status IS NULL ORDER BY name ASC LIMIT 200");
    $customers = [];
    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $customers[] = [
                'id' => (int)$row['id'],
                'name' => $row['name'],
                'phone' => $row['phone'] ?? ''
            ];
        }
    }

    echo json_encode([
        'status' => 'success',
        'customers' => $customers
    ]);
    exit;
}

// 3. SAVE ORDER TO DATABASE (STRICT REAL DATA)
if ($action === 'save_order') {
    $customer_name = trim($_POST['customer_name'] ?? $json_data['customer_name'] ?? '');
    $items = $_POST['items'] ?? $json_data['items'] ?? [];
    $user_id = isset($_POST['user_id']) ? intval($_POST['user_id']) : (isset($json_data['user_id']) ? intval($json_data['user_id']) : 1);

    if (empty($customer_name) || empty($items)) {
        echo json_encode(['status' => 'error', 'message' => 'بيانات الطلب غير مكتملة']);
        exit;
    }

    // Auto-register Customer if missing
    $cust_check = $conn->prepare("SELECT id FROM customers WHERE name = ?");
    $cust_check->bind_param("s", $customer_name);
    $cust_check->execute();
    $cust_res = $cust_check->get_result();

    if ($cust_res->num_rows === 0) {
        $ins_cust = $conn->prepare("INSERT INTO customers (tenant_id, name, phone, created_at) VALUES (1, ?, 'زبون جديد مضاف من التطبيق', NOW())");
        $ins_cust->bind_param("s", $customer_name);
        $ins_cust->execute();
        $ins_cust->close();
    }
    $cust_check->close();

    // Check if customer already has a form in the current active shift
    $shift = getActiveShiftTimes();
    $start_str = $shift['start_str'];
    $end_str = $shift['end_str'];

    $stmt_existing = $conn->prepare("
        SELECT id FROM forms 
        WHERE tenant_id = 1 AND customer_name = ? AND created_at >= ? AND created_at < ?
        ORDER BY id ASC LIMIT 1
    ");
    $stmt_existing->bind_param("sss", $customer_name, $start_str, $end_str);
    $stmt_existing->execute();
    $res_existing = $stmt_existing->get_result();

    $form_id = 0;
    $is_merged = false;

    if ($res_existing && $row_existing = $res_existing->fetch_assoc()) {
        $form_id = (int)$row_existing['id'];
        $is_merged = true;
    }
    $stmt_existing->close();

    if ($form_id === 0) {
        // Insert new Form
        $materials_count = count($items);
        $stmt_form = $conn->prepare("INSERT INTO forms (tenant_id, user_id, customer_name, materials_count, status, grand_total, created_at) VALUES (1, ?, ?, ?, 'جديد', 0.00, NOW())");
        $stmt_form->bind_param("isi", $user_id, $customer_name, $materials_count);

        if ($stmt_form->execute()) {
            $form_id = $conn->insert_id;
            $stmt_form->close();
        } else {
            echo json_encode([
                'status' => 'error',
                'message' => 'فشل حفظ الطلب: ' . $conn->error
            ]);
            exit;
        }
    }

    if ($form_id > 0) {
        // Insert Form Items
        $stmt_item = $conn->prepare("INSERT INTO form_items (tenant_id, form_id, name, quantity, weight, price, worker_share, commission, commission_10, total, created_at) VALUES (1, ?, ?, ?, ?, 0.00, 0.00, 0.00, 0.00, 0.00, NOW())");

        foreach ($items as $item) {
            $item_name = isset($item['materialName']) ? $item['materialName'] : (isset($item['name']) ? $item['name'] : '');
            $qty = isset($item['count']) ? intval($item['count']) : (isset($item['quantity']) ? intval($item['quantity']) : 1);
            $w = isset($item['weight']) ? floatval($item['weight']) : 0.00;

            $stmt_item->bind_param("isid", $form_id, $item_name, $qty, $w);
            $stmt_item->execute();
        }
        $stmt_item->close();

        // Update total materials_count for the form
        $count_res = $conn->query("SELECT COUNT(*) AS total_items FROM form_items WHERE form_id = $form_id");
        if ($count_res && $row_c = $count_res->fetch_assoc()) {
            $total_m_count = intval($row_c['total_items']);
            $conn->query("UPDATE forms SET materials_count = $total_m_count WHERE id = $form_id");
        }

        updateSystemState($conn, 'forms');
        updateSystemState($conn, 'customers');

        echo json_encode([
            'status' => 'success',
            'message' => $is_merged 
                ? 'تم دمج المواد بنجاح في استمارة الزبون الحالية لهذا اليوم' 
                : 'تم فتح استمارة جديدة للزبون بنجاح',
            'form_id' => $form_id,
            'merged' => $is_merged
        ]);
    } else {
        echo json_encode([
            'status' => 'error',
            'message' => 'فشل حفظ الطلب'
        ]);
    }
    exit;
}

// 4. GET ORDERS FOR DYNAMIC ACTIVE SHIFT STRICTLY FROM DATABASE
if ($action === 'get_orders') {
    $shift = getActiveShiftTimes();
    $start_str = $shift['start_str'];
    $end_str = $shift['end_str'];

    $stmt = $conn->prepare("
        SELECT id, customer_name, materials_count, status, grand_total, created_at 
        FROM forms 
        WHERE tenant_id = 1 AND created_at >= ? AND created_at < ?
        ORDER BY created_at DESC
    ");
    $stmt->bind_param("ss", $start_str, $end_str);
    $stmt->execute();
    $res = $stmt->get_result();

    $orders = [];
    if ($res) {
        while ($form = $res->fetch_assoc()) {
            $form_id = $form['id'];

            // Fetch Items for this form
            $stmt_items = $conn->prepare("SELECT name, quantity, weight FROM form_items WHERE form_id = ?");
            $stmt_items->bind_param("i", $form_id);
            $stmt_items->execute();
            $items_res = $stmt_items->get_result();

            $items = [];
            $total_weight = 0.0;
            $total_count = 0;

            if ($items_res) {
                while ($it = $items_res->fetch_assoc()) {
                    $w = floatval($it['weight']);
                    $q = intval($it['quantity']);
                    $total_weight += $w;
                    $total_count += $q;

                    $items[] = [
                        'materialId' => $form_id,
                        'materialName' => $it['name'],
                        'jallab' => 'محلي',
                        'accountingType' => $w > 0 ? 'وزن * سعر' : 'عدد * سعر',
                        'weight' => $w,
                        'count' => $q
                    ];
                }
            }
            $stmt_items->close();

            $date_formatted = date('Y/m/d h:i a', strtotime($form['created_at']));
            $date_formatted = str_replace(['AM', 'PM', 'am', 'pm'], ['ص', 'م', 'ص', 'م'], $date_formatted);

            $orders[] = [
                'id' => 'ORD-' . $form['id'],
                'customerName' => $form['customer_name'],
                'date' => $date_formatted,
                'timestamp' => strtotime($form['created_at']) * 1000,
                'items' => $items,
                'totalWeight' => $total_weight,
                'totalCount' => $total_count
            ];
        }
    }
    $stmt->close();

    echo json_encode([
        'status' => 'success',
        'shift_text' => $shift['shift_text'],
        'orders' => $orders
    ]);
    exit;
}

// 5. DELETE ORDER
if ($action === 'delete_order') {
    $form_id = isset($_GET['form_id']) ? intval($_GET['form_id']) : 0;

    if ($form_id > 0) {
        $conn->query("DELETE FROM form_items WHERE form_id = $form_id");
        $conn->query("DELETE FROM forms WHERE id = $form_id");
        updateSystemState($conn, 'forms');
        echo json_encode(['status' => 'success', 'message' => 'تم حذف الطلب']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'معرف الطلب غير صحيح']);
    }
    exit;
}

echo json_encode(['status' => 'error', 'message' => 'إجراء غير معروف']);
