<?php
session_start();
include_once('includes/config.php');

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

$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['create_table'])) {
    // Create complaints table
    $createTableQuery = "
    CREATE TABLE IF NOT EXISTS `tblcomplaints` (
        `ID` int(11) NOT NULL AUTO_INCREMENT,
        `ComplaintNumber` varchar(50) NOT NULL,
        `CustomerID` int(11) NOT NULL,
        `RiceBagID` int(11) NOT NULL,
        `ComplaintType` enum('Quality','Quantity','Delivery','Pricing','Service','Other') NOT NULL DEFAULT 'Quality',
        `ComplaintTitle` varchar(200) NOT NULL,
        `ComplaintDescription` text NOT NULL,
        `ComplaintDate` date NOT NULL,
        `ComplaintTime` time NOT NULL,
        `Priority` enum('Low','Medium','High') NOT NULL DEFAULT 'Medium',
        `Status` enum('Pending','In Progress','Resolved','Closed') NOT NULL DEFAULT 'Pending',
        `Resolution` text DEFAULT NULL,
        `ResolvedDate` date DEFAULT NULL,
        `ResolvedBy` int(11) DEFAULT NULL,
        `CreatedBy` int(11) NOT NULL,
        `CreatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
        `UpdatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        `IsActive` tinyint(1) NOT NULL DEFAULT 1,
        PRIMARY KEY (`ID`),
        UNIQUE KEY `ComplaintNumber` (`ComplaintNumber`),
        KEY `CustomerID` (`CustomerID`),
        KEY `RiceBagID` (`RiceBagID`),
        KEY `CreatedBy` (`CreatedBy`),
        KEY `ResolvedBy` (`ResolvedBy`),
        KEY `Status` (`Status`),
        KEY `Priority` (`Priority`),
        KEY `ComplaintDate` (`ComplaintDate`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
    
    if (mysqli_query($con, $createTableQuery)) {
        $message = "Complaints table created successfully!";
        
        // Insert sample data
        $sampleData = "
        INSERT IGNORE INTO `tblcomplaints` 
        (`ComplaintNumber`, `CustomerID`, `RiceBagID`, `ComplaintType`, `ComplaintTitle`, `ComplaintDescription`, `ComplaintDate`, `ComplaintTime`, `Priority`, `Status`, `CreatedBy`) 
        VALUES 
        ('COMP-20250920-001', 1, 1, 'Quality', 'Rice quality issue', 'The rice bags received have some quality issues with mixed varieties', CURDATE(), CURTIME(), 'Medium', 'Pending', {$_SESSION['uid']}),
        ('COMP-20250920-002', 2, 2, 'Delivery', 'Late delivery', 'Order was delivered 2 days late causing inconvenience', CURDATE(), CURTIME(), 'High', 'In Progress', {$_SESSION['uid']}),
        ('COMP-20250919-003', 3, 1, 'Quantity', 'Short quantity', 'Received 48kg instead of 50kg as ordered', DATE_SUB(CURDATE(), INTERVAL 1 DAY), '14:30:00', 'High', 'Resolved', {$_SESSION['uid']});
        ";
        
        if (mysqli_multi_query($con, $sampleData)) {
            $message .= " Sample complaint data inserted!";
        }
        
    } else {
        $error = "Error creating table: " . mysqli_error($con);
    }
}

// Check current status
$tableExists = false;
$recordCount = 0;

$checkTable = mysqli_query($con, "SHOW TABLES LIKE 'tblcomplaints'");
if ($checkTable && mysqli_num_rows($checkTable) > 0) {
    $tableExists = true;
    $countResult = mysqli_query($con, "SELECT COUNT(*) as count FROM tblcomplaints");
    if ($countResult) {
        $recordCount = mysqli_fetch_assoc($countResult)['count'];
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Setup Complaints Table</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="css/sb-admin-2.min.css" rel="stylesheet">
</head>
<body>
    <div class="container-fluid">
        <div class="row justify-content-center">
            <div class="col-xl-6 col-lg-8 col-md-10">
                <div class="card o-hidden border-0 shadow-lg my-5">
                    <div class="card-body p-0">
                        <div class="row">
                            <div class="col-lg-12">
                                <div class="p-5">
                                    <div class="text-center">
                                        <h1 class="h4 text-gray-900 mb-4">Setup Complaints Management</h1>
                                    </div>
                                    
                                    <?php if ($message): ?>
                                        <div class="alert alert-success">
                                            <i class="fas fa-check-circle mr-2"></i><?php echo $message; ?>
                                        </div>
                                    <?php endif; ?>
                                    
                                    <?php if ($error): ?>
                                        <div class="alert alert-danger">
                                            <i class="fas fa-exclamation-triangle mr-2"></i><?php echo $error; ?>
                                        </div>
                                    <?php endif; ?>
                                    
                                    <div class="mb-4">
                                        <h5>Current Status:</h5>
                                        <ul class="list-group">
                                            <li class="list-group-item d-flex justify-content-between align-items-center">
                                                Complaints Table
                                                <?php if ($tableExists): ?>
                                                    <span class="badge badge-success badge-pill">
                                                        <i class="fas fa-check mr-1"></i>Exists
                                                    </span>
                                                <?php else: ?>
                                                    <span class="badge badge-danger badge-pill">
                                                        <i class="fas fa-times mr-1"></i>Missing
                                                    </span>
                                                <?php endif; ?>
                                            </li>
                                            <li class="list-group-item d-flex justify-content-between align-items-center">
                                                Total Complaints
                                                <span class="badge badge-primary badge-pill"><?php echo $recordCount; ?></span>
                                            </li>
                                        </ul>
                                    </div>
                                    
                                    <?php if (!$tableExists || $recordCount == 0): ?>
                                        <form method="POST">
                                            <button type="submit" name="create_table" class="btn btn-primary btn-user btn-block">
                                                <i class="fas fa-database mr-2"></i>
                                                <?php echo !$tableExists ? 'Create Complaints Table & Add Sample Data' : 'Add Sample Data'; ?>
                                            </button>
                                        </form>
                                        <hr>
                                    <?php endif; ?>
                                    
                                    <div class="text-center">
                                        <a class="btn btn-secondary" href="test-database.php">
                                            <i class="fas fa-search mr-2"></i>Database Test
                                        </a>
                                        <a class="btn btn-success ml-2" href="complaints-management.php">
                                            <i class="fas fa-comment-dots mr-2"></i>Go to Complaints
                                        </a>
                                    </div>
                                    
                                    <hr>
                                    <div class="text-center">
                                        <a class="btn btn-link" href="dashboard.php">
                                            <i class="fas fa-arrow-left mr-1"></i>Back to Dashboard
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap core JavaScript-->
    <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>
</body>
</html>