<?php
session_start();
require_once('db.php'); // Assuming you have a database connection file

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

// Fetch current user
$user_id = $_SESSION['user_id'];
$query = "SELECT * FROM users WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();

// Check user role
$is_manager = (isset($_SESSION['user_role']) && $_SESSION['user_role'] == 'manager');

// Get all leads with "Won" status
$won_leads = [];
$stmt = $conn->prepare("SELECT l.*, c.company_name AS client_name, c.email, c.phone 
                       FROM leads l 
                       LEFT JOIN clients c ON l.client_id = c.id 
                       WHERE l.status = 'won'");
$stmt->execute();
$won_leads = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Get sent project notifications (for both manager and regular users)
$sent_projects = [];
$stmt = $conn->prepare("SELECT n.*, u.name AS sender_name 
                       FROM notifications n 
                       JOIN users u ON n.sender_id = u.id");
$stmt->execute();
$sent_projects = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['send_to_manager'])) {
        // Send message to manager and store in notifications
        $project_name = $_POST['project_name'];
        $client_name = $_POST['client_name'];
        $email = $_POST['email'];
        $phone = $_POST['phone'];
        $budget = $_POST['budget'];
        $requirements = $_POST['requirements'];
        $lead_id = $_POST['lead_id'];
        
        // Use the logged-in user's ID as sender_id
        $sender_id = $_SESSION['user_id'];
        
        // Query to find the first available user ID as receiver_id
        $receiver_query = "SELECT id FROM users LIMIT 1";
        $receiver_result = $conn->query($receiver_query);
        $receiver_id = $receiver_result->fetch_assoc()['id'] ?? 1; // Default to 1 if no user found
        
        // Insert into notifications table
        $stmt = $conn->prepare("INSERT INTO notifications (sender_id, receiver_id, project_name, client_name, email, phone, budget, requirements, status, created_at) 
                               VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'unread', NOW())");
        $stmt->bind_param("iissssds", $sender_id, $receiver_id, $project_name, $client_name, $email, $phone, $budget, $requirements);

        if ($stmt->execute()) {
            $_SESSION['success'] = "Project sent to manager successfully!";
        } else {
            $_SESSION['error'] = "Error: Failed to send project to manager.";
        }
    } elseif (isset($_POST['update_project']) && $is_manager) {
        // Manager updates project
        $lead_id = $_POST['lead_id'];
        $project_name = $_POST['project_name'];
        $client_name = $_POST['client_name'];
        $email = $_POST['email'];
        $phone = $_POST['phone'];
        $budget = $_POST['budget'];
        $requirements = $_POST['requirements'];
        
        // Update notifications table
        $stmt = $conn->prepare("UPDATE notifications SET 
                              project_name = ?, 
                              client_name = ?, 
                              email = ?, 
                              phone = ?, 
                              budget = ?, 
                              requirements = ? 
                              WHERE id = ?");
        $stmt->bind_param("ssssdsi", $project_name, $client_name, $email, $phone, $budget, $requirements, $lead_id);
        $stmt->execute();
        
        $_SESSION['success'] = "Project updated successfully!";
    }
    
    header("Location: project.php");
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Projects | Decconz Admin Dashboard</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta content="A fully featured admin theme which can be used to build CRM, CMS, etc." name="description">
    <meta content="Coderthemes" name="author">

    <!-- App favicon -->
    <link rel="shortcut icon" href="images/favicon.ico">

    <!-- Theme Config Js -->
    <script src="js/hyper-config.js"></script>

    <!-- Vendor css -->
    <link href="css/vendor.min.css" rel="stylesheet" type="text/css">

    <!-- App css -->
    <link href="css/app.min.css" rel="stylesheet" type="text/css" id="app-style">

    <!-- Icons css -->
    <link href="css/unicons.css" rel="stylesheet" type="text/css">
    <link href="css/remixicon.css" rel="stylesheet" type="text/css">
    <link href="css/materialdesignicons.min.css" rel="stylesheet" type="text/css">
</head>

<body>
    <!-- Begin page -->
    <div class="wrapper">
        
        <!-- ========== Topbar Start ========== -->
        <?php include('includes/nav.php') ?>
        <!-- ========== Topbar End ========== -->

        <!-- ========== Left Sidebar Start ========== -->
        <?php include('includes/sidebar.php') ?>
        <!-- ========== Left Sidebar End ========== -->

        <!-- ============================================================== -->
        <!-- Start Page Content here -->
        <!-- ============================================================== -->

        <div class="content-page">
            <div class="content">

                <!-- Start Content-->
                <div class="container-fluid">
                    
                    <!-- start page title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box">
                                <h4 class="page-title">Projects</h4>
                            </div>
                        </div>
                    </div>     
                    <!-- end page title --> 

                    <?php if (isset($_SESSION['success'])): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    <?php endif; ?>

                    <?php if (isset($_SESSION['error'])): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['error']; unset($_SESSION['error']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    <?php endif; ?>

                    <!-- Won Leads Section -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <h4 class="header-title">Won Leads</h4>
                                    <p class="text-muted font-14">List of all leads with 'Won' status</p>

                                    <div class="table-responsive">
                                        <table class="table table-centered mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Client Name</th>
                                                    <th>Email</th>
                                                    <th>Phone</th>
                                                    <th>Value</th>
                                                    <th>Notes</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($won_leads as $lead): ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars($lead['client_name'] ?? 'N/A'); ?></td>
                                                    <td><?php echo htmlspecialchars($lead['email'] ?? 'N/A'); ?></td>
                                                    <td><?php echo htmlspecialchars($lead['phone'] ?? 'N/A'); ?></td>
                                                    <td><?php echo htmlspecialchars($lead['value'] ?? 'N/A'); ?></td>
                                                    <td><?php echo htmlspecialchars($lead['notes'] ?? 'N/A'); ?></td>
                                                    <td>
                                                        <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#leadModal<?php echo $lead['id']; ?>">
                                                            <?php echo $is_manager ? 'Update Project' : 'Send to Manager'; ?>
                                                        </button>
                                                    </td>
                                                </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div> <!-- end table-responsive -->
                                </div> <!-- end card-body -->
                            </div> <!-- end card -->
                        </div> <!-- end col -->
                    </div> <!-- end row -->

                    <!-- Sent Projects Section -->
                    <div class="row mt-4">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <h4 class="header-title">Sent Projects</h4>
                                    <p class="text-muted font-14">List of projects sent to manager</p>

                                    <div class="table-responsive">
                                        <table class="table table-centered mb-0">
                                            <thead>
                                                <tr>
                                                    <th>ID</th>
                                                    <th>Project Name</th>
                                                    <th>Client Name</th>
                                                    <th>Email</th>
                                                    <th>Phone</th>
                                                    <th>Budget</th>
                                                    <th>Requirements</th>
                                                    <th>Status</th>
                                                    <?php if ($is_manager): ?>
                                                    <th>Actions</th>
                                                    <?php endif; ?>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($sent_projects as $project): ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars($project['id'] ?? 'N/A'); ?></td>
                                                    <td><?php echo htmlspecialchars($project['project_name'] ?? 'N/A'); ?></td>
                                                    <td><?php echo htmlspecialchars($project['client_name'] ?? 'N/A'); ?></td>
                                                    <td><?php echo htmlspecialchars($project['email'] ?? 'N/A'); ?></td>
                                                    <td><?php echo htmlspecialchars($project['phone'] ?? 'N/A'); ?></td>
                                                    <td><?php echo htmlspecialchars($project['budget'] ?? 'N/A'); ?></td>
                                                    <td><?php echo htmlspecialchars($project['requirements'] ?? 'N/A'); ?></td>
                                                    <td><?php echo htmlspecialchars($project['status']); ?></td>
                                                    <?php if ($is_manager): ?>
                                                    <td>
                                                        <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#leadModal<?php echo $project['id']; ?>">
                                                            Update Project
                                                        </button>
                                                    </td>
                                                    <?php endif; ?>
                                                </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div> <!-- end table-responsive -->
                                </div> <!-- end card-body -->
                            </div> <!-- end card -->
                        </div> <!-- end col -->
                    </div> <!-- end row>
                    
                </div> <!-- container -->

            </div> <!-- content -->

            <!-- Footer Start -->
            <?php include('includes/footer.php') ?>
            <!-- end Footer -->

        </div>

        <!-- ============================================================== -->
        <!-- End Page content -->
        <!-- ============================================================== -->

    </div>
    <!-- END wrapper -->

    <!-- Theme Settings -->
    <?php include('includes/theme.php') ?>

    <!-- Vendor js -->
    <script src="js/vendor.min.js"></script>

    <!-- App js -->
    <script src="js/app.js"></script>

    <!-- Apex Charts js -->
    <script src="js/apexcharts.min.js"></script>

    <!-- Todo js -->
    <script src="js/component.todo.js"></script>

    <!-- CRM Dashboard Demo App Js -->
    <script src="js/demo.crm-dashboard.js"></script>

    <!-- Modal for each lead -->
    <?php foreach ($won_leads as $lead): ?>
    <div class="modal fade" id="leadModal<?php echo $lead['id']; ?>" tabindex="-1" role="dialog" aria-labelledby="leadModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="leadModalLabel"><?php echo $is_manager ? 'Update Project' : 'Send to Manager'; ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="POST" action="project.php">
                    <div class="modal-body">
                        <input type="hidden" name="lead_id" value="<?php echo $lead['id']; ?>">
                        
                        <div class="mb-3">
                            <label for="project_name_<?php echo $lead['id']; ?>" class="form-label">Project Name</label>
                            <input type="text" class="form-control" id="project_name_<?php echo $lead['id']; ?>" name="project_name" value="<?php echo htmlspecialchars($lead['project_name'] ?? ''); ?>" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="client_name_<?php echo $lead['id']; ?>" class="form-label">Client Name</label>
                            <input type="text" class="form-control" id="client_name_<?php echo $lead['id']; ?>" name="client_name" value="<?php echo htmlspecialchars($lead['client_name'] ?? ''); ?>" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="email_<?php echo $lead['id']; ?>" class="form-label">Email</label>
                            <input type="email" class="form-control" id="email_<?php echo $lead['id']; ?>" name="email" value="<?php echo htmlspecialchars($lead['email'] ?? ''); ?>" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="phone_<?php echo $lead['id']; ?>" class="form-label">Phone</label>
                            <input type="text" class="form-control" id="phone_<?php echo $lead['id']; ?>" name="phone" value="<?php echo htmlspecialchars($lead['phone'] ?? ''); ?>" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="budget_<?php echo $lead['id']; ?>" class="form-label">Budget</label>
                            <input type="text" class="form-control" id="budget_<?php echo $lead['id']; ?>" name="budget" value="<?php echo htmlspecialchars($lead['value'] ?? ''); ?>" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="requirements_<?php echo $lead['id']; ?>" class="form-label">Client Requirements</label>
                            <textarea class="form-control" id="requirements_<?php echo $lead['id']; ?>" name="requirements" rows="3" required><?php echo htmlspecialchars($lead['notes'] ?? ''); ?></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        <button type="submit" name="<?php echo $is_manager ? 'update_project' : 'send_to_manager'; ?>" class="btn btn-primary">
                            <?php echo $is_manager ? 'Update Project' : 'Send to Manager'; ?>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <?php endforeach; ?>

    <!-- Modal for each sent project -->
    <?php foreach ($sent_projects as $project): ?>
    <div class="modal fade" id="leadModal<?php echo $project['id']; ?>" tabindex="-1" role="dialog" aria-labelledby="leadModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="leadModalLabel">Update Project</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="POST" action="project.php">
                    <div class="modal-body">
                        <input type="hidden" name="lead_id" value="<?php echo $project['id']; ?>">
                        
                        <div class="mb-3">
                            <label for="project_name_<?php echo $project['id']; ?>" class="form-label">Project Name</label>
                            <input type="text" class="form-control" id="project_name_<?php echo $project['id']; ?>" name="project_name" value="<?php echo htmlspecialchars($project['project_name'] ?? ''); ?>" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="client_name_<?php echo $project['id']; ?>" class="form-label">Client Name</label>
                            <input type="text" class="form-control" id="client_name_<?php echo $project['id']; ?>" name="client_name" value="<?php echo htmlspecialchars($project['client_name'] ?? ''); ?>" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="email_<?php echo $project['id']; ?>" class="form-label">Email</label>
                            <input type="email" class="form-control" id="email_<?php echo $project['id']; ?>" name="email" value="<?php echo htmlspecialchars($project['email'] ?? ''); ?>" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="phone_<?php echo $project['id']; ?>" class="form-label">Phone</label>
                            <input type="text" class="form-control" id="phone_<?php echo $project['id']; ?>" name="phone" value="<?php echo htmlspecialchars($project['phone'] ?? 'N/A'); ?>" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="budget_<?php echo $project['id']; ?>" class="form-label">Budget</label>
                            <input type="text" class="form-control" id="budget_<?php echo $project['id']; ?>" name="budget" value="<?php echo htmlspecialchars($project['budget'] ?? ''); ?>" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="requirements_<?php echo $project['id']; ?>" class="form-label">Client Requirements</label>
                            <textarea class="form-control" id="requirements_<?php echo $project['id']; ?>" name="requirements" rows="3" required><?php echo htmlspecialchars($project['requirements'] ?? ''); ?></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        <button type="submit" name="update_project" class="btn btn-primary">Update Project</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <?php endforeach; ?>

</body>
</html>