<?php
/*
 * user_popup.php
 * AJAX endpoint for the User Management popup.
 *
 * Requires:
 *   - config.inc.php with a mysqli connection in $conn
 *   - admin login session: $_SESSION['admin_id']
 *
 * If your config uses another connection variable, change $conn below.
 */

require_once __DIR__ . '/config.inc.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

header('Content-Type: application/json; charset=utf-8');

if (!isset($_SESSION['admin_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Please login as administrator.']);
    exit;
}

if (!isset($conn) || !($conn instanceof mysqli)) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database connection ($conn) was not found.']);
    exit;
}

$conn->set_charset('utf8mb4');

function out($data, $code = 200) {
    http_response_code($code);
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

function post_string($key, $default = '') {
    return isset($_POST[$key]) ? trim((string)$_POST[$key]) : $default;
}

function post_int($key, $default = 0) {
    return isset($_POST[$key]) ? (int)$_POST[$key] : $default;
}

function post_float($key, $default = 0) {
    return isset($_POST[$key]) ? (float)$_POST[$key] : $default;
}

function stmt_or_fail($conn, $sql) {
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        out(['success' => false, 'message' => 'Database error: ' . $conn->error], 500);
    }
    return $stmt;
}

$action = $_GET['action'] ?? $_POST['action'] ?? 'details';
$user_id = (int)($_GET['user_id'] ?? $_POST['user_id'] ?? 0);

if ($user_id <= 0) {
    out(['success' => false, 'message' => 'Invalid user ID.'], 400);
}

/* ---------------------------------------------------------
   GET USER DETAILS
   --------------------------------------------------------- */
if ($action === 'details') {
    $stmt = stmt_or_fail($conn, "
        SELECT id, full_name, phone, email, address, account_status, created_at
        FROM users
        WHERE id = ?
        LIMIT 1
    ");
    $stmt->bind_param('i', $user_id);
    $stmt->execute();
    $user = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if (!$user) {
        out(['success' => false, 'message' => 'User not found.'], 404);
    }

    $stmt = stmt_or_fail($conn, "
        SELECT
            o.id,
            o.total_amount,
            o.created_at,
            o.status,
            COALESCE(o.admin_comment, '') AS admin_comment
        FROM orders o
        WHERE o.user_id = ?
        ORDER BY o.id DESC
    ");
    $stmt->bind_param('i', $user_id);
    $stmt->execute();
    $orders_rs = $stmt->get_result();
    $orders = [];

    while ($order = $orders_rs->fetch_assoc()) {
        $order_id = (int)$order['id'];

        $item_stmt = stmt_or_fail($conn, "
            SELECT
                oi.id,
                oi.product_id,
                oi.quantity,
                oi.quantity_delivered,
                oi.unit_price,
                oi.subtotal,
                p.display_model,
                COALESCE(b.name, '') AS product_brand,
                COALESCE(dt.name, '') AS display_type,
                COALESCE(
                    (SELECT SUM(r.quantity)
                     FROM order_returns r
                     WHERE r.order_item_id = oi.id), 0
                ) AS returned_quantity,
                COALESCE(
                    (SELECT SUM(r.total_amount)
                     FROM order_returns r
                     WHERE r.order_item_id = oi.id), 0
                ) AS returned_amount
            FROM order_items oi
            INNER JOIN products p ON p.id = oi.product_id
            LEFT JOIN brands b ON b.id = p.brand_id
            LEFT JOIN display_types dt ON dt.id = oi.display_type_id
            WHERE oi.order_id = ?
            ORDER BY oi.id ASC
        ");
        $item_stmt->bind_param('i', $order_id);
        $item_stmt->execute();
        $items_rs = $item_stmt->get_result();

        $items = [];
        while ($item = $items_rs->fetch_assoc()) {
            $item['id'] = (int)$item['id'];
            $item['quantity'] = (int)$item['quantity'];
            $item['quantity_delivered'] = (int)$item['quantity_delivered'];
            $item['returned_quantity'] = (int)$item['returned_quantity'];
            $item['unit_price'] = (float)$item['unit_price'];
            $item['subtotal'] = (float)$item['subtotal'];
            $item['returned_amount'] = (float)$item['returned_amount'];

            $available_return_qty =
                max(0, $item['quantity_delivered'] - $item['returned_quantity']);

            $item['available_return_qty'] = $available_return_qty;
            $item['description'] =
                trim($item['product_brand'] . ' ' . $item['display_model']) .
                ($item['display_type'] ? ' - ' . $item['display_type'] : '');

            $items[] = $item;
        }
        $item_stmt->close();

        $order['id'] = $order_id;
        $order['total_amount'] = (float)$order['total_amount'];
        $order['items'] = $items;
        $orders[] = $order;
    }
    $stmt->close();

    $stmt = stmt_or_fail($conn, "
        SELECT
            id, order_id, amount, payment_date,
            payment_method, COALESCE(reference_no, '') reference_no,
            COALESCE(notes, '') notes
        FROM user_payments
        WHERE user_id = ?
        ORDER BY payment_date DESC, id DESC
    ");
    $stmt->bind_param('i', $user_id);
    $stmt->execute();
    $payments_rs = $stmt->get_result();
    $payments = [];
    $received = 0.0;

    while ($payment = $payments_rs->fetch_assoc()) {
        $payment['id'] = (int)$payment['id'];
        $payment['order_id'] = $payment['order_id'] !== null ? (int)$payment['order_id'] : null;
        $payment['amount'] = (float)$payment['amount'];
        $received += $payment['amount'];
        $payments[] = $payment;
    }
    $stmt->close();

    $stmt = stmt_or_fail($conn, "
        SELECT
            r.id,
            r.order_id,
            r.order_item_id,
            r.quantity,
            r.unit_price,
            r.total_amount,
            r.return_date,
            COALESCE(r.reason, '') reason,
            COALESCE(p.display_model, '') display_model,
            COALESCE(b.name, '') product_brand
        FROM order_returns r
        INNER JOIN order_items oi ON oi.id = r.order_item_id
        INNER JOIN products p ON p.id = oi.product_id
        LEFT JOIN brands b ON b.id = p.brand_id
        WHERE r.user_id = ?
        ORDER BY r.return_date DESC, r.id DESC
    ");
    $stmt->bind_param('i', $user_id);
    $stmt->execute();
    $returns_rs = $stmt->get_result();
    $returns = [];
    $returned_total = 0.0;

    while ($ret = $returns_rs->fetch_assoc()) {
        $ret['id'] = (int)$ret['id'];
        $ret['order_id'] = (int)$ret['order_id'];
        $ret['order_item_id'] = (int)$ret['order_item_id'];
        $ret['quantity'] = (int)$ret['quantity'];
        $ret['unit_price'] = (float)$ret['unit_price'];
        $ret['total_amount'] = (float)$ret['total_amount'];
        $returned_total += $ret['total_amount'];
        $ret['description'] =
            trim($ret['product_brand'] . ' ' . $ret['display_model']);
        $returns[] = $ret;
    }
    $stmt->close();

    $stmt = stmt_or_fail($conn, "
        SELECT
            w.id,
            w.order_id,
            w.order_item_id,
            w.warranty_title,
            w.warranty_start,
            w.warranty_end,
            w.warranty_status,
            COALESCE(w.notes, '') notes,
            COALESCE(p.display_model, '') display_model,
            COALESCE(b.name, '') product_brand
        FROM user_warranties w
        LEFT JOIN order_items oi ON oi.id = w.order_item_id
        LEFT JOIN products p ON p.id = oi.product_id
        LEFT JOIN brands b ON b.id = p.brand_id
        WHERE w.user_id = ?
        ORDER BY w.warranty_end DESC, w.id DESC
    ");
    $stmt->bind_param('i', $user_id);
    $stmt->execute();
    $warranty_rs = $stmt->get_result();
    $warranties = [];

    while ($w = $warranty_rs->fetch_assoc()) {
        $w['id'] = (int)$w['id'];
        $warranties[] = $w;
    }
    $stmt->close();

    $gross_total = 0.0;
    foreach ($orders as $o) {
        $gross_total += $o['total_amount'];
    }

    /* Returned goods reduce the amount the customer owes. */
    $net_total = max(0, $gross_total - $returned_total);
    $balance = $net_total - $received;

    out([
        'success' => true,
        'user' => $user,
        'orders' => $orders,
        'payments' => $payments,
        'returns' => $returns,
        'warranties' => $warranties,
        'summary' => [
            'gross_total' => round($gross_total, 2),
            'returned_total' => round($returned_total, 2),
            'net_total' => round($net_total, 2),
            'received_total' => round($received, 2),
            'balance' => round($balance, 2)
        ]
    ]);
}


/* ---------------------------------------------------------
   ADD PAYMENT
   --------------------------------------------------------- */
if ($action === 'add_payment') {
    $amount = post_float('amount');
    $order_id = post_int('order_id', 0);
    $payment_date = post_string('payment_date');
    $payment_method = post_string('payment_method', 'Cash');
    $reference_no = post_string('reference_no');
    $notes = post_string('notes');

    if ($amount <= 0) {
        out(['success' => false, 'message' => 'Payment amount must be greater than zero.'], 400);
    }

    if ($payment_date === '') {
        $payment_date = date('Y-m-d H:i:s');
    } elseif (strlen($payment_date) === 16) {
        $payment_date = str_replace('T', ' ', $payment_date) . ':00';
    }

    if ($order_id > 0) {
        $check = stmt_or_fail($conn, "
            SELECT id FROM orders WHERE id = ? AND user_id = ? LIMIT 1
        ");
        $check->bind_param('ii', $order_id, $user_id);
        $check->execute();
        $exists = $check->get_result()->fetch_assoc();
        $check->close();

        if (!$exists) {
            out(['success' => false, 'message' => 'Selected order does not belong to this user.'], 400);
        }
    } else {
        $order_id = null;
    }

    $admin_id = (int)$_SESSION['admin_id'];

    $stmt = stmt_or_fail($conn, "
        INSERT INTO user_payments
        (user_id, order_id, amount, payment_date, payment_method, reference_no, notes, created_by)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->bind_param(
        'iidssssi',
        $user_id,
        $order_id,
        $amount,
        $payment_date,
        $payment_method,
        $reference_no,
        $notes,
        $admin_id
    );

    if (!$stmt->execute()) {
        $msg = $stmt->error;
        $stmt->close();
        out(['success' => false, 'message' => $msg], 500);
    }

    $stmt->close();
    out(['success' => true, 'message' => 'Payment added successfully.']);
}


/* ---------------------------------------------------------
   ADD WARRANTY
   --------------------------------------------------------- */
if ($action === 'add_warranty') {
    $order_id = post_int('order_id', 0);
    $order_item_id = post_int('order_item_id', 0);
    $title = post_string('warranty_title', 'Product Warranty');
    $start = post_string('warranty_start');
    $end = post_string('warranty_end');
    $notes = post_string('notes');

    if ($start === '' || $end === '') {
        out(['success' => false, 'message' => 'Warranty start and end dates are required.'], 400);
    }

    if ($end < $start) {
        out(['success' => false, 'message' => 'Warranty end date cannot be before start date.'], 400);
    }

    if ($order_id > 0) {
        $check = stmt_or_fail($conn, "
            SELECT id FROM orders WHERE id = ? AND user_id = ? LIMIT 1
        ");
        $check->bind_param('ii', $order_id, $user_id);
        $check->execute();
        $ok = $check->get_result()->fetch_assoc();
        $check->close();

        if (!$ok) {
            out(['success' => false, 'message' => 'Invalid order for this user.'], 400);
        }
    } else {
        $order_id = null;
    }

    if ($order_item_id > 0) {
        $check = stmt_or_fail($conn, "
            SELECT oi.id
            FROM order_items oi
            INNER JOIN orders o ON o.id = oi.order_id
            WHERE oi.id = ? AND o.user_id = ?
            LIMIT 1
        ");
        $check->bind_param('ii', $order_item_id, $user_id);
        $check->execute();
        $ok = $check->get_result()->fetch_assoc();
        $check->close();

        if (!$ok) {
            out(['success' => false, 'message' => 'Invalid order item for this user.'], 400);
        }
    } else {
        $order_item_id = null;
    }

    $admin_id = (int)$_SESSION['admin_id'];

    $stmt = stmt_or_fail($conn, "
        INSERT INTO user_warranties
        (user_id, order_id, order_item_id, warranty_title,
         warranty_start, warranty_end, notes, created_by)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->bind_param(
        'iiissssi',
        $user_id,
        $order_id,
        $order_item_id,
        $title,
        $start,
        $end,
        $notes,
        $admin_id
    );

    if (!$stmt->execute()) {
        $msg = $stmt->error;
        $stmt->close();
        out(['success' => false, 'message' => $msg], 500);
    }

    $stmt->close();
    out(['success' => true, 'message' => 'Warranty added successfully.']);
}


/* ---------------------------------------------------------
   ADD RETURN
   Price is read from the selected order item on the server.
   Total = quantity * unit price.
   --------------------------------------------------------- */
if ($action === 'add_return') {
    $order_id = post_int('order_id');
    $order_item_id = post_int('order_item_id');
    $quantity = post_int('quantity');
    $reason = post_string('reason');
    $notes = post_string('notes');

    if ($order_id <= 0 || $order_item_id <= 0 || $quantity <= 0) {
        out(['success' => false, 'message' => 'Order, item and quantity are required.'], 400);
    }

    $stmt = stmt_or_fail($conn, "
        SELECT
            oi.id,
            oi.order_id,
            oi.quantity_delivered,
            oi.unit_price,
            COALESCE(
                (SELECT SUM(r.quantity)
                 FROM order_returns r
                 WHERE r.order_item_id = oi.id), 0
            ) AS already_returned
        FROM order_items oi
        INNER JOIN orders o ON o.id = oi.order_id
        WHERE oi.id = ? AND oi.order_id = ? AND o.user_id = ?
        LIMIT 1
    ");
    $stmt->bind_param('iii', $order_item_id, $order_id, $user_id);
    $stmt->execute();
    $item = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if (!$item) {
        out(['success' => false, 'message' => 'Invalid order item.'], 400);
    }

    $already_returned = (int)$item['already_returned'];
    $available = max(0, (int)$item['quantity_delivered'] - $already_returned);

    if ($quantity > $available) {
        out([
            'success' => false,
            'message' => "Only {$available} item(s) are available for return."
        ], 400);
    }

    $unit_price = (float)$item['unit_price'];
    $total_amount = round($unit_price * $quantity, 2);
    $admin_id = (int)$_SESSION['admin_id'];

    $stmt = stmt_or_fail($conn, "
        INSERT INTO order_returns
        (user_id, order_id, order_item_id, quantity, unit_price,
         total_amount, reason, notes, created_by)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->bind_param(
        'iiiiddssi',
        $user_id,
        $order_id,
        $order_item_id,
        $quantity,
        $unit_price,
        $total_amount,
        $reason,
        $notes,
        $admin_id
    );

    if (!$stmt->execute()) {
        $msg = $stmt->error;
        $stmt->close();
        out(['success' => false, 'message' => $msg], 500);
    }

    $stmt->close();

    out([
        'success' => true,
        'message' => 'Return recorded successfully.',
        'unit_price' => $unit_price,
        'quantity' => $quantity,
        'total_amount' => $total_amount
    ]);
}


/* ---------------------------------------------------------
   DELETE PAYMENT / WARRANTY / RETURN
   --------------------------------------------------------- */
if ($action === 'delete_payment') {
    $id = post_int('id');

    $stmt = stmt_or_fail($conn, "DELETE FROM user_payments WHERE id = ? AND user_id = ?");
    $stmt->bind_param('ii', $id, $user_id);
    $stmt->execute();
    $stmt->close();

    out(['success' => true, 'message' => 'Payment deleted.']);
}

if ($action === 'delete_warranty') {
    $id = post_int('id');

    $stmt = stmt_or_fail($conn, "DELETE FROM user_warranties WHERE id = ? AND user_id = ?");
    $stmt->bind_param('ii', $id, $user_id);
    $stmt->execute();
    $stmt->close();

    out(['success' => true, 'message' => 'Warranty deleted.']);
}

if ($action === 'delete_return') {
    $id = post_int('id');

    $stmt = stmt_or_fail($conn, "DELETE FROM order_returns WHERE id = ? AND user_id = ?");
    $stmt->bind_param('ii', $id, $user_id);
    $stmt->execute();
    $stmt->close();

    out(['success' => true, 'message' => 'Return deleted.']);
}

out(['success' => false, 'message' => 'Unknown action.'], 400);
?>
