<!----------------------------------Login------------------------------------>
<?php
include 'php/db_connection.php';

// শুধুমাত্র লগইন করা ইউজার পেজ দেখতে পারবে
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$userName = $_SESSION['user_name'];
$role = $_SESSION['role']; // ✅ এখানে role সেভ করা হচ্ছে
$userId = $_SESSION['user_id'];


$isAdmin = ($_SESSION['role'] == 'admin');

?>

<!---------------------------------কন্টেন------------------------------------>
<?php
$con->set_charset("utf8mb4");

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

$sql = "
    SELECT * FROM customer 
    WHERE customer_name LIKE ? OR customer_phone LIKE ?
";
$stmt = $con->prepare($sql);
$search_param = "%$search%";
$stmt->bind_param("ss", $search_param, $search_param);
$stmt->execute();
$result = $stmt->get_result();

$customer = $result->fetch_assoc();

if (!$customer) {
    die("কোনো কাস্টমার পাওয়া যায়নি।");
}

// হিসাব বের করা
$customer_id = $customer['id'];

$total_sales_sql = "SELECT SUM(grand_total) AS total_sales FROM sales WHERE customer_id = ?";
$stmt = $con->prepare($total_sales_sql);
$stmt->bind_param("i", $customer_id);
$stmt->execute();
$total_sales = $stmt->get_result()->fetch_assoc()['total_sales'] ?? 0;

$total_collected_sql = "SELECT SUM(collected_amount) AS total_collected FROM due_collections WHERE customer_id = ?";
$stmt = $con->prepare($total_collected_sql);
$stmt->bind_param("i", $customer_id);
$stmt->execute();
$total_collected = $stmt->get_result()->fetch_assoc()['total_collected'] ?? 0;

$total_due = $total_sales - $total_collected;

// 🖨️ প্রিন্ট/ভিউ অংশ
echo "<h2>{$customer['Customer_name']} ({$customer['Customer_phone']})</h2>";
echo "<p><strong>ঠিকানা:</strong> {$customer['Customer_address']}</p>";
echo "<p><strong>মোট ক্রয়:</strong> {$total_sales} টাকা</p>";
echo "<p><strong>মোট জমা:</strong> {$total_collected} টাকা</p>";
echo "<p><strong>বাকি আছে:</strong> {$total_due} টাকা</p>";

// 🧾 Purchase History
echo "<h3>Purchase History:</h3>";
$purchase_sql = "SELECT created_at, grand_total FROM sales WHERE customer_id = ? ORDER BY created_at DESC";
$stmt = $con->prepare($purchase_sql);
$stmt->bind_param("i", $customer_id);
$stmt->execute();
$purchases = $stmt->get_result();

while ($row = $purchases->fetch_assoc()) {
    echo "<p>{$row['created_at']} - {$row['grand_total']} টাকা</p>";
}

// 💵 Collection History
echo "<h3>Collection History:</h3>";
$collection_sql = "SELECT collected_at, collected_amount FROM due_collections WHERE customer_id = ? ORDER BY collected_at DESC";
$stmt = $con->prepare($collection_sql);
$stmt->bind_param("i", $customer_id);
$stmt->execute();
$collections = $stmt->get_result();

while ($row = $collections->fetch_assoc()) {
    echo "<p>{$row['collected_at']} - জমা: {$row['collected_amount']} টাকা</p>";
}

echo "<br><a href='export_pdf.php?customer_id=$customer_id' target='_blank'>PDF আকারে ডাউনলোড করুন</a>";
?>
