<?php
session_start();
include 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Check if user has permission (admin only for approval)
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT username, user_role, full_name, email, role_id FROM users WHERE user_id = $user_id";
$result_user_details = $conn->query($sql_user_details);

if ($result_user_details && $row_user_details = $result_user_details->fetch_assoc()) {
    $username = $row_user_details['username'];
    $user_role = $row_user_details['user_role'];
    $full_name = $row_user_details['full_name'];
    $email = $row_user_details['email'];
    $role_id = $row_user_details['role_id'];
}

// Restrict access to admin role only
if ($role_id != 1) {
    $_SESSION['error_message'] = "You don't have permission to approve withdrawals.";
    header('Location: cheque_withdrawals.php');
    exit();
}

// Check if withdrawal ID is provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    $_SESSION['error_message'] = "No withdrawal ID provided";
    header('Location: cheque_withdrawals.php');
    exit();
}

$withdrawal_id = intval($_GET['id']);

// Format date helper function
function formatDate($date) {
    if (empty($date) || $date == '0000-00-00' || $date == '0000-00-00 00:00:00') {
        return 'N/A';
    }
    return date('Y-m-d', strtotime($date));
}

// Get withdrawal details
$sql = "
    SELECT 
        w.*,
        u1.full_name as requester_name
    FROM 
        cheque_withdrawals w
    LEFT JOIN 
        users u1 ON w.withdrawal_user_id = u1.user_id
    WHERE 
        w.id = ?
";

$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $withdrawal_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['error_message'] = "Withdrawal not found";
    header('Location: cheque_withdrawals.php');
    exit();
}

$withdrawal = $result->fetch_assoc();

// Check if already approved or rejected
if ($withdrawal['status'] !== 'pending') {
    $_SESSION['error_message'] = "This withdrawal request has already been " . $withdrawal['status'];
    header('Location: view_withdrawal.php?id=' . $withdrawal_id);
    exit();
}

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'];
    $rejection_reason = isset($_POST['rejection_reason']) ? $_POST['rejection_reason'] : '';
    
    try {
        if ($action === 'approve') {
            // Approve the withdrawal
            $sql = "UPDATE cheque_withdrawals SET 
                    status = 'approved', 
                    approval_user_id = ?, 
                    approved_at = NOW() 
                    WHERE id = ?";
            
            $stmt = $conn->prepare($sql);
            $stmt->bind_param('ii', $user_id, $withdrawal_id);
            
            if ($stmt->execute()) {
                $_SESSION['success_message'] = "Withdrawal request approved successfully.";
                header('Location: view_withdrawal.php?id=' . $withdrawal_id);
                exit();
            } else {
                throw new Exception($stmt->error);
            }
        } elseif ($action === 'reject') {
            // Validate rejection reason
            if (empty($rejection_reason)) {
                $_SESSION['error_message'] = "Rejection reason is required.";
                header('Location: approve_withdrawal.php?id=' . $withdrawal_id);
                exit();
            }
            
            // Reject the withdrawal
            $sql = "UPDATE cheque_withdrawals SET 
                    status = 'rejected', 
                    approval_user_id = ?, 
                    rejected_at = NOW(),
                    rejection_reason = ?
                    WHERE id = ?";
            
            $stmt = $conn->prepare($sql);
            $stmt->bind_param('isi', $user_id, $rejection_reason, $withdrawal_id);
            
            if ($stmt->execute()) {
                $_SESSION['success_message'] = "Withdrawal request rejected.";
                header('Location: view_withdrawal.php?id=' . $withdrawal_id);
                exit();
            } else {
                throw new Exception($stmt->error);
            }
        } else {
            throw new Exception("Invalid action");
        }
    } catch (Exception $e) {
        $_SESSION['error_message'] = "Error processing withdrawal: " . $e->getMessage();
        header('Location: approve_withdrawal.php?id=' . $withdrawal_id);
        exit();
    }
}

// Get system name from settings
$sql_settings = "SELECT setting_value FROM settings WHERE setting_key = 'system_name'";
$result_settings = $conn->query($sql_settings);
if ($result_settings && $result_settings->num_rows > 0) {
    $row_settings = $result_settings->fetch_assoc();
    $system_name = $row_settings['setting_value'];
} else {
    $system_name = "Royal Freight Management System";
}
?>

<?php include 'layouts/main.php'; ?>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Approve Cheque Withdrawal')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- Sweet Alert css -->
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
    
    <style>
        .detail-card {
            margin-bottom: 1.5rem;
        }
        .detail-header {
            background-color: #f8f9fa;
            border-bottom: 1px solid #e9e9ef;
            padding: 1rem;
        }
        .detail-label {
            font-weight: 600;
            margin-bottom: 5px;
            color: #495057;
        }
        .detail-value {
            margin-bottom: 15px;
        }
        .action-card {
            background-color: #f8f9fc;
            border: 1px solid #e9ecef;
            border-radius: 0.25rem;
            padding: 20px;
        }
        .action-btns {
            margin-top: 20px;
        }
    </style>
</head>

<body>
    <!-- Begin page -->
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <!-- ============================================================== -->
        <!-- Start right Content here -->
        <!-- ============================================================== -->
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Finance Management', 'title' => 'Approve Cheque Withdrawal')); ?>

                    <?php
                    // Show success message if set
                    if (isset($_SESSION['success_message'])) {
                        echo '<div class="alert alert-success alert-dismissible fade show" role="alert">';
                        echo $_SESSION['success_message'];
                        echo '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>';
                        echo '</div>';
                        unset($_SESSION['success_message']);
                    }
                    
                    // Show error message if set
                    if (isset($_SESSION['error_message'])) {
                        echo '<div class="alert alert-danger alert-dismissible fade show" role="alert">';
                        echo $_SESSION['error_message'];
                        echo '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>';
                        echo '</div>';
                        unset($_SESSION['error_message']);
                    }
                    ?>

                    <div class="row">
                        <div class="col-lg-8">
                            <!-- Withdrawal details -->
                            <div class="card detail-card">
                                <div class="card-header detail-header">
                                    <h4 class="card-title mb-0">Cheque Withdrawal #<?php echo $withdrawal_id; ?></h4>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="detail-label">Withdrawal Date</div>
                                            <div class="detail-value"><?php echo formatDate($withdrawal['withdrawal_date']); ?></div>
                                            
                                            <div class="detail-label">Amount</div>
                                            <div class="detail-value">
                                                <strong><?php echo $withdrawal['currency'] . ' ' . number_format($withdrawal['amount'], 2); ?></strong>
                                            </div>
                                            
                                            <div class="detail-label">Bank</div>
                                            <div class="detail-value"><?php echo $withdrawal['bank']; ?></div>
                                            
                                            <?php if (!empty($withdrawal['bank_branch'])): ?>
                                            <div class="detail-label">Bank Branch</div>
                                            <div class="detail-value"><?php echo $withdrawal['bank_branch']; ?></div>
                                            <?php endif; ?>
                                            
                                            <?php if (!empty($withdrawal['cheque_number'])): ?>
                                            <div class="detail-label">Cheque Number</div>
                                            <div class="detail-value"><?php echo $withdrawal['cheque_number']; ?></div>
                                            <?php endif; ?>
                                        </div>
                                        
                                        <div class="col-md-6">
                                            <div class="detail-label">Requested By</div>
                                            <div class="detail-value"><?php echo $withdrawal['requester_name']; ?></div>
                                            
                                            <div class="detail-label">Request Date</div>
                                            <div class="detail-value"><?php echo formatDate($withdrawal['created_at']); ?></div>
                                            
                                            <div class="detail-label">Status</div>
                                            <div class="detail-value">
                                                <span class="badge bg-warning">Pending</span>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="row mt-4">
                                        <div class="col-12">
                                            <div class="detail-label">Purpose</div>
                                            <div class="detail-value">
                                                <?php echo nl2br(htmlspecialchars($withdrawal['purpose'])); ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-lg-4">
                            <!-- Approval/Rejection action card -->
                            <div class="card">
                                <div class="card-header detail-header">
                                    <h4 class="card-title mb-0">Approval Action</h4>
                                </div>
                                <div class="card-body">
                                    <div class="action-card">
                                        <h5 class="mb-3">Make a Decision</h5>
                                        <p>Please review the withdrawal request details and make a decision to approve or reject.</p>
                                        
                                        <div class="mt-4">
                                            <div class="form-check mb-3">
                                                <input class="form-check-input" type="radio" name="decision" id="approve-option" value="approve" checked>
                                                <label class="form-check-label" for="approve-option">
                                                    Approve this withdrawal request
                                                </label>
                                            </div>
                                            <div class="form-check">
                                                <input class="form-check-input" type="radio" name="decision" id="reject-option" value="reject">
                                                <label class="form-check-label" for="reject-option">
                                                    Reject this withdrawal request
                                                </label>
                                            </div>
                                        </div>
                                        
                                        <div id="rejection-reason-container" class="mt-3" style="display: none;">
                                            <label for="rejection-reason" class="form-label">Rejection Reason</label>
                                            <textarea class="form-control" id="rejection-reason" rows="4" placeholder="Please provide a reason for rejection"></textarea>
                                            <div class="form-text text-danger">This reason will be visible to the requester.</div>
                                        </div>
                                        
                                        <div class="action-btns d-flex justify-content-between mt-4">
                                            <a href="view_withdrawal.php?id=<?php echo $withdrawal_id; ?>" class="btn btn-secondary">
                                                Cancel
                                            </a>
                                            <button id="confirm-action-btn" class="btn btn-primary">
                                                Confirm Approval
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- container-fluid -->
            </div>
            <!-- End Page-content -->

            <?php include 'layouts/footer.php'; ?>
        </div>
        <!-- end main content-->
    </div>
    <!-- END layout-wrapper -->

    <!-- Hidden form for submission -->
    <form id="action-form" method="POST" action="" style="display: none;">
        <input type="hidden" id="action-input" name="action" value="approve">
        <input type="hidden" id="rejection-reason-input" name="rejection_reason" value="">
    </form>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Toggle rejection reason textarea based on selected option
            $('input[name="decision"]').change(function() {
                const decision = $('input[name="decision"]:checked').val();
                
                if (decision === 'reject') {
                    $('#rejection-reason-container').show();
                    $('#confirm-action-btn').text('Confirm Rejection');
                    $('#confirm-action-btn').removeClass('btn-primary').addClass('btn-danger');
                } else {
                    $('#rejection-reason-container').hide();
                    $('#confirm-action-btn').text('Confirm Approval');
                    $('#confirm-action-btn').removeClass('btn-danger').addClass('btn-primary');
                }
            });
            
            // Handle confirmation button click
            $('#confirm-action-btn').click(function() {
                const decision = $('input[name="decision"]:checked').val();
                let valid = true;
                
                if (decision === 'reject') {
                    const reason = $('#rejection-reason').val().trim();
                    if (reason === '') {
                        Swal.fire({
                            icon: 'error',
                            title: 'Rejection Reason Required',
                            text: 'Please provide a reason for rejection.',
                            confirmButtonColor: '#3085d6'
                        });
                        valid = false;
                    } else {
                        $('#rejection-reason-input').val(reason);
                    }
                }
                
                if (valid) {
                    $('#action-input').val(decision);
                    
                    const confirmText = decision === 'approve' ? 
                        'Are you sure you want to approve this withdrawal request?' : 
                        'Are you sure you want to reject this withdrawal request?';
                    
                    const confirmBtnText = decision === 'approve' ? 'Yes, approve it!' : 'Yes, reject it!';
                    const confirmBtnColor = decision === 'approve' ? '#3085d6' : '#d33';
                    
                    Swal.fire({
                        title: 'Confirm Action',
                        text: confirmText,
                        icon: 'question',
                        showCancelButton: true,
                        confirmButtonColor: confirmBtnColor,
                        cancelButtonColor: '#6c757d',
                        confirmButtonText: confirmBtnText
                    }).then((result) => {
                        if (result.isConfirmed) {
                            $('#action-form').submit();
                        }
                    });
                }
            });
        });
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>