<?php
include("db/cn.php");
include("common/tx.php");
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
ob_start();
//session_start(); // Make sure session is started

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'];
} else {
    echo '<script type="text/javascript">window.location.href="logout.php";</script>';
    exit();
}

// ==========================
// Get cr_id from URL with validation
// ==========================
$cr_id = isset($_GET['cr_id']) ? (int)$_GET['cr_id'] : null;

if (!$cr_id || $cr_id <= 0) {
    $_SESSION['error_message'] = "Invalid Customer ID provided.";
    echo '<script type="text/javascript">window.location.href="view_creditor.php";</script>';
    exit();
}

// ==========================
// Update Record
// ==========================
if (isset($_POST['update'])) {
    $cr_name      = mysqli_real_escape_string($connection, $_POST['cr_name']);
    $cr_nickname  = mysqli_real_escape_string($connection, $_POST['cr_nickname']);
    $cr_address   = mysqli_real_escape_string($connection, $_POST['cr_address']);
    $phone_number = mysqli_real_escape_string($connection, $_POST['phone_number']);
    $date_time    = mysqli_real_escape_string($connection, $_POST['date_time']);
    $openAmount   = mysqli_real_escape_string($connection, $_POST['opening_balance']);
    $cr_id        = (int)$_POST['cr_id'];

    // Start transaction
    mysqli_begin_transaction($connection);
    
    try {
        // Update credit_note table
        $update = $connection->prepare("
            UPDATE credit_note SET
                cr_name = ?,
                cr_nickname = ?,
                cr_address = ?,
                phone_number = ?,
                date_time = ?
            WHERE cr_id = ?
        ");

        $update->bind_param(
            "sssssi",
            $cr_name,
            $cr_nickname,
            $cr_address,
            $phone_number,
            $date_time,
            $cr_id
        );

        if (!$update->execute()) {
            throw new Exception("Failed to update credit note: " . $update->error);
        }

        // Update creditor_opening_amount table
        $update_opening = $connection->prepare("
            UPDATE creditor_opening_amount 
            SET open_amount = ? 
            WHERE creditor_name = ?
        ");
        
        $update_opening->bind_param("ds", $openAmount, $cr_name);
        
        if (!$update_opening->execute()) {
            throw new Exception("Failed to update opening balance: " . $update_opening->error);
        }

        // If everything is successful, commit the transaction
        mysqli_commit($connection);
        $success = "Customer Updated Successfully";
        
        // Refresh the data after update
        $select = $connection->prepare("SELECT * FROM credit_note WHERE cr_id = ?");
        $select->bind_param("i", $cr_id);
        $select->execute();
        $data = $select->get_result()->fetch_assoc();
        
    } catch (Exception $e) {
        // Rollback transaction on error
        mysqli_rollback($connection);
        $error = "Update Failed: " . $e->getMessage();
    }
}

// ==========================
// Fetch Existing Record
// ==========================
if (!isset($data)) {
    $select = $connection->prepare("SELECT * FROM credit_note WHERE cr_id = ?");
    $select->bind_param("i", $cr_id);
    $select->execute();
    $data = $select->get_result()->fetch_assoc();
    
    if (!$data) {
        $_SESSION['error_message'] = "Record Not Found with ID: " . $cr_id;
        echo '<script type="text/javascript">window.location.href="view_creditor.php";</script>';
        exit();
    }
}

// Fetch opening balance
$crName = $data['cr_name'];
$opening_query = mysqli_query($connection, "SELECT * FROM creditor_opening_amount WHERE creditor_name = '$crName'");
$opening_data = mysqli_fetch_array($opening_query);
$opening_balance = $opening_data ? $opening_data['open_amount'] : 0;

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><?php echo $tx; ?> - Edit Customer</title>
    <link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">
    <link href="../css/sb-admin-2.min.css" rel="stylesheet">
    <link href="../css/sb-admin-2.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <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 #0A4657 solid;
        }
        .btn-primary:hover {
            background: #fff;
            border: 1px #0A4657 solid;
            color: #0A4657;
        }
        .fa-download:hover {
            color: #953E39;
        }
        .form-control {
            font-weight: 700;
            color: #000;
        }
        .btn {
            font-weight: 700;
        }
        .required:after {
            content: " *";
            color: red;
        }
    </style>
</head>
<body id="page-top">

    <!-- Page Wrapper -->
    <div id="wrapper">

        <!-- Sidebar -->
        <?php include("common/sd.php"); ?>
        <!-- End of Sidebar -->

        <!-- Content Wrapper -->
        <div id="content-wrapper" class="d-flex flex-column">

            <!-- Main Content -->
            <div id="content">

                <!-- Topbar -->
                <nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow">
                    <!-- Sidebar Toggle (Topbar) -->
                    <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>
                <!-- End of Topbar -->

                <!-- Begin Page Content -->
                <div class="container-fluid">
                    <?php if (!empty($success)) : ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <i class="fas fa-check-circle"></i> <?= htmlspecialchars($success) ?>
                            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                    <?php endif; ?>

                    <?php if (!empty($error)) : ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="fas fa-exclamation-triangle"></i> <?= htmlspecialchars($error) ?>
                            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                    <?php endif; ?>

                    <!-- Page Heading -->
                    <div class="d-sm-flex align-items-center justify-content-between mb-4">
                        <h1 class="h3 mb-0 text-gray-800">Edit Customer Detail</h1>
                        <a href="view_creditor.php" class="d-none d-sm-inline-block btn btn-sm btn-primary shadow-sm">
                            <i class="fas fa-list fa-sm text-white-50"></i> Back to Customer List
                        </a>
                    </div>

                    <div class="row">
                        <div class="col-lg-3"></div>
                        <div class="col-lg-6">
                            <div class="card shadow mb-4">
                                <div class="card-header py-3">
                                    <h6 class="m-0 font-weight-bold text-primary">Customer Information</h6>
                                </div>
                                <div class="card-body">
                                    <form method="POST" action="" onsubmit="return validateForm()">
                                        <input type="hidden" name="cr_id" value="<?= htmlspecialchars($data['cr_id']) ?>">
                                        
                                        <div class="mb-3">
                                            <label class="form-label required">Customer Name</label>
                                            <input type="text" name="cr_name" class="form-control"
                                                   value="<?= htmlspecialchars($data['cr_name']) ?>" required>
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">Nick Name</label>
                                            <input type="text" name="cr_nickname" class="form-control"
                                                   value="<?= htmlspecialchars($data['cr_nickname']) ?>">
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">Address</label>
                                            <textarea name="cr_address" class="form-control" rows="3"><?= htmlspecialchars($data['cr_address']) ?></textarea>
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">Phone Number</label>
                                            <input type="tel" name="phone_number" class="form-control"
                                                   value="<?= htmlspecialchars($data['phone_number']) ?>"
                                                   pattern="[0-9+\-\s]+" title="Please enter a valid phone number">
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">Date & Time</label>
                                            <input type="datetime-local" name="date_time" class="form-control"
                                                   value="<?= date('Y-m-d\TH:i', strtotime($data['date_time'])) ?>" required>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label class="form-label">Opening Balance</label>
                                            <input type="number" step="0.01" name="opening_balance" class="form-control"
                                                   value="<?= htmlspecialchars($opening_balance) ?>">
                                            <small class="text-muted">Positive amount means customer owes you, negative means you owe customer</small>
                                        </div>
                                        
                                        <div class="mb-3 text-center">
                                            <button type="submit" name="update" class="btn btn-primary">
                                                <i class="fas fa-save"></i> Update Record
                                            </button>
                                            <a href="view_creditor.php" class="btn btn-secondary">
                                                <i class="fas fa-times"></i> Cancel
                                            </a>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-3"></div>
                    </div>
                </div>
                <!-- /.container-fluid -->

            </div>
            <!-- End of Main Content -->

            <!-- Footer -->
            <?php include("common/main_ft.php"); ?>
            <!-- End of Footer -->

        </div>
        <!-- End of Content Wrapper -->

    </div>
    <!-- End of Page Wrapper -->

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

    <!-- Logout Modal-->
    <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.php">Logout</a>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Form validation
        function validateForm() {
            var customerName = document.forms[0]["cr_name"].value;
            if (customerName == "") {
                alert("Customer Name is required!");
                return false;
            }
            return true;
        }
        
        // Auto-hide alerts after 5 seconds
        setTimeout(function() {
            var alerts = document.querySelectorAll('.alert');
            alerts.forEach(function(alert) {
                var bsAlert = new bootstrap.Alert(alert);
                setTimeout(function() {
                    bsAlert.close();
                }, 5000);
            });
        }, 1000);
    </script> 

    <!-- Bootstrap core JavaScript-->
    <script src="../vendor/jquery/jquery.min.js"></script>
    <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

    <!-- Core plugin JavaScript-->
    <script src="../vendor/jquery-easing/jquery.easing.min.js"></script>

    <!-- Custom scripts for all pages-->
    <script src="../js/sb-admin-2.min.js"></script>

</body>
</html>