<?php
include("db/cn.php");
ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Session check (unchanged)
if (isset($_SESSION['user_name']) && isset($_SESSION['user_role']) && isset($_SESSION['outlet_name']) && isset($_SESSION['outlet_address'])) {
    $userName = $_SESSION['user_name'];
    $userRole = $_SESSION['user_role'];
    $outlet_address = $_SESSION['outlet_address'];
    $outlet_name = $_SESSION['outlet_name'];
}

// Fetch city-transport pairs for dropdown and auto-fill
$cities = []; // associative array city => transport
$city_query = "SELECT DISTINCT city, transport FROM loc_trans ORDER BY city";
$city_result = $connection->query($city_query);
if ($city_result && $city_result->num_rows > 0) {
    while ($row = $city_result->fetch_assoc()) {
        $cities[$row['city']] = $row['transport'];
    }
}
$city_result->free();

// Form submission handling
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["creditor"])) {
    $date_time32  = date("Y-m-d");
    $cr_name      = $_POST["cr_name"];
    $cr_address   = $_POST["cr_address"];
    $phone_number = $_POST["phone_number"];
    $cr_id        = $_POST["cr_id"];
    $amount       = $_POST["amount"];
    $city         = $_POST["city"] ?? '';
    $transport    = $_POST["transport"] ?? '';

    // Updated query with city and transport
    $stmt = $connection->prepare("
        INSERT INTO credit_note 
        (cr_name, cr_address, phone_number, cr_id, user_name, user_role, outlet_name, outlet_address, date_time, city, transport) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->bind_param(
        "sssssssssss",
        $cr_name,
        $cr_address,
        $phone_number,
        $cr_id,
        $userName,
        $userRole,
        $outlet_name,
        $outlet_address,
        $date_time32,
        $city,
        $transport
    );

    if ($stmt->execute()) {
        // Insert opening amount (unchanged)
        mysqli_query($connection, "INSERT INTO creditor_opening_amount (creditor_name, open_amount, paid_by, date_time)
        VALUES ('$cr_name', '$amount', 'cash', '$date_time32')");
        
        echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
        <script type="text/javascript">
            Swal.fire({
                icon: "success",
                title: "Customer added successfully!",
                showConfirmButton: false,
                timer: 2000
            }).then(function() {
                window.location.href = "view_creditor.php";
            });
        </script>';
    } else {
        echo "Error: " . $stmt->error;
    }
    $stmt->close();
}
ob_end_flush();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Customer Ledger</title>
    <!-- Font Awesome -->
    <link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <!-- Google Font -->
    <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">
    <!-- SB Admin 2 styles -->
    <link href="../css/sb-admin-2.min.css" rel="stylesheet">
    <link href="../css/sb-admin-2.css" rel="stylesheet">
    <!-- Chart.js (if needed later) -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>

<style>
    body {
        font-family: 'Quicksand', sans-serif;
    }
    .chart-container {
        position: relative;
        background: rgba(255, 255, 255, 0.9);
        border-radius: 10px;
        padding: 15px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    }
    canvas {
        max-width: 100%;
        height: auto;
    }
    .bg-gradient-primary {
        background: #0A4657;
        color: #fff;
    }
    .btn-primary {
        background: #0A4657;
        color: #fff;
        border: 1px solid #0A4657;
    }
    .btn-primary:hover {
        background: #fff;
        border: 1px solid #0A4657;
        color: #0A4657;
    }
    .fa-download:hover {
        color: #953E39;
    }
    .form-control {
        font-weight: 700;
        color: #000;
        border-radius: 8px;
    }
    .form-control:focus {
        border-color: #0A4657;
        box-shadow: 0 0 0 0.2rem rgba(10, 70, 87, 0.25);
    }
    .card-custom {
        border: none;
        border-radius: 15px;
        box-shadow: 0 0.5rem 1.5rem rgba(0,0,0,0.1);
        background: #fff;
    }
    .card-header-custom {
        background: linear-gradient(135deg, #0A4657, #18748A);
        color: white;
        border-radius: 15px 15px 0 0;
    }
    label {
        font-weight: 600;
        color: #0A4657;
        margin-bottom: 5px;
    }
</style>

<body id="page-top">
    <div id="wrapper">
        <?php include("common/sd.php"); ?>

        <div id="content-wrapper" class="d-flex flex-column">
            <div id="content">
                <nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow">
                    <button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3">
                        <i class="fa fa-bars"></i>
                    </button>
                    <?php include('common/log.php'); ?>
                </nav>

                <div class="container">
                    <div class="row mb-4">
                        <div class="col-12">
                            <h3 style="color:#0A4657; font-weight:700;">
                                <i class="fas fa-user-plus mr-2"></i> Add Customer Ledger
                            </h3>
                        </div>
                    </div>

                    <div class="card card-custom">
                        <div class="card-header card-header-custom">
                            <h5 class="mb-0"><i class="fas fa-credit-card mr-2"></i> New Creditor Details</h5>
                        </div>
                        <div class="card-body">
                            <form action="credits.php" method="post" enctype="multipart/form-data">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label><i class="fas fa-id-badge mr-1"></i> Customer ID</label>
                                            <input class="form-control" type="text" name="cr_id" value="<?php 
                                                $pr_id2 = str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);
                                                echo $pr_id2; ?>" readonly>
                                        </div>
                                        <div class="form-group">
                                            <label><i class="fas fa-user mr-1"></i> Customer Name</label>
                                            <input class="form-control" type="text" name="cr_name" placeholder="Enter full name" >
                                        </div>
                                        <div class="form-group">
                                            <label><i class="fas fa-map-marker-alt mr-1"></i> City</label>
                                            <select class="form-control" name="city" id="city" onchange="updateTransport()" >
                                                <option value="" disabled selected>-- Select City --</option>
                                                <?php foreach ($cities as $city_name => $trans): ?>
                                                    <option value="<?php echo htmlspecialchars($city_name); ?>">
                                                        <?php echo htmlspecialchars($city_name); ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div class="form-group">
                                            <label><i class="fas fa-truck mr-1"></i> Transport</label>
                                            <input class="form-control" type="text" name="transport" id="transport" readonly placeholder="Auto-filled after city selection">
                                        </div>
                                        <div class="form-group">
                                            <label><i class="fas fa-dollar-sign mr-1"></i> Opening Amount</label>
                                            <input class="form-control" type="number" step="0.01" name="amount" placeholder="0.00" >
                                        </div>
                                    </div>

                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label><i class="fas fa-address-card mr-1"></i> Customer Address</label>
                                            <input class="form-control" type="text" name="cr_address" placeholder="Full address" >
                                        </div>
                                        <div class="form-group">
                                            <label><i class="fas fa-phone-alt mr-1"></i> Phone Number</label>
                                            <input class="form-control" type="text" name="phone_number" placeholder="e.g. 0300-1234567" >
                                        </div>
                                        <!-- Hidden cr_nickname field (if needed) -->
                                        <input type="hidden" name="cr_nickname" value="">
                                        <button type="submit" class="btn btn-primary btn-lg btn-block mt-4" name="creditor">
                                            <i class="fas fa-save mr-2"></i> Save Creditor
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>

                <br><br>
                <?php include("common/main_ft.php"); ?>
            </div>
        </div>

        <a class="scroll-to-top rounded" href="#page-top">
            <i class="fas fa-angle-up"></i>
        </a>

        <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5>
                        <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">×</span>
                        </button>
                    </div>
                    <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>
                    <div class="modal-footer">
                        <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
                        <a class="btn btn-primary" href="">Logout</a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap & jQuery -->
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js"></script>
    <script src="../vendor/jquery/jquery.min.js"></script>
    <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="../vendor/jquery-easing/jquery.easing.min.js"></script>
    <script src="../js/sb-admin-2.min.js"></script>

    <!-- Auto-fill transport based on selected city -->
    <script>
        // City -> Transport mapping from PHP
        var cityTransport = <?php echo json_encode($cities); ?>;

        function updateTransport() {
            var citySelect = document.getElementById('city');
            var transportInput = document.getElementById('transport');
            var selectedCity = citySelect.value;
            
            if (selectedCity && cityTransport[selectedCity]) {
                transportInput.value = cityTransport[selectedCity];
            } else {
                transportInput.value = '';
            }
        }

        // Pre-fill if a city is already selected (e.g., after form validation fail)
        document.addEventListener('DOMContentLoaded', function() {
            updateTransport();
        });
    </script>

    <link rel="stylesheet" href="../css/responsive-mobile.css">
    <script src="../js/responsive-mobile.js"></script>
</body>
</html>