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

// Set content type to JSON
header('Content-Type: application/json');

// Check if user is logged in
if (!isset($_SESSION['uid'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$userId = $_SESSION['uid'];

// Check if complaints table exists
function checkComplaintsTable($con) {
    $result = mysqli_query($con, "SHOW TABLES LIKE 'tblcomplaints'");
    return $result && mysqli_num_rows($result) > 0;
}

try {
    // Check if table exists
    if (!checkComplaintsTable($con)) {
        echo json_encode([
            'success' => false,
            'error' => 'Complaints table not found. Please run setup-complaints.php to create the table.',
            'setup_required' => true
        ]);
        exit();
    }
    
    // Get request method and action
    $method = $_SERVER['REQUEST_METHOD'];
    $action = $_GET['action'] ?? '';
    
    switch ($method) {
        case 'GET':
            if ($action === 'stats') {
                getStats();
            } elseif (isset($_GET['id'])) {
                getComplaint($_GET['id']);
            } else {
                getAllComplaints();
            }
            break;
            
        case 'POST':
            createComplaint();
            break;
            
        case 'PUT':
            updateComplaint();
            break;
            
        default:
            echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

// Get all complaints with filtering
function getAllComplaints() {
    global $con;
    
    $status = $_GET['status'] ?? '';
    $priority = $_GET['priority'] ?? '';
    $search = $_GET['search'] ?? '';
    
    $whereConditions = ["c.IsActive = 1"];
    
    if (!empty($status) && $status !== 'all') {
        $whereConditions[] = "c.Status = '" . mysqli_real_escape_string($con, $status) . "'";
    }
    
    if (!empty($priority)) {
        $whereConditions[] = "c.Priority = '" . mysqli_real_escape_string($con, $priority) . "'";
    }
    
    if (!empty($search)) {
        $search = mysqli_real_escape_string($con, $search);
        $whereConditions[] = "(c.ComplaintNumber LIKE '%$search%' OR c.ComplaintTitle LIKE '%$search%' OR c.ComplaintDescription LIKE '%$search%')";
    }
    
    $whereClause = "WHERE " . implode(" AND ", $whereConditions);
    
    $query = "
        SELECT 
            c.ID,
            c.ComplaintNumber,
            c.ComplaintType,
            c.ComplaintTitle,
            c.ComplaintDescription,
            c.ComplaintDate,
            c.ComplaintTime,
            c.Priority,
            c.Status,
            c.Resolution,
            c.ResolvedDate,
            c.CreatedAt,
            c.CustomerID,
            c.RiceBagID,
            'Unknown Customer' as CustomerName,
            'N/A' as Mobile,
            'N/A' as Area,
            'N/A' as RiceBagName,
            'N/A' as Brand,
            'System' as CreatedByName,
            'N/A' as ResolvedByName
        FROM tblcomplaints c
        $whereClause
        ORDER BY c.ComplaintDate DESC, c.ComplaintTime DESC, c.ID DESC
    ";
    
    $result = mysqli_query($con, $query);
    $complaints = [];
    
    if ($result) {
        while ($row = mysqli_fetch_assoc($result)) {
            $complaints[] = $row;
        }
    }
    
    echo json_encode([
        'success' => true,
        'data' => $complaints,
        'total' => count($complaints)
    ]);
}

// Get complaint statistics
function getStats() {
    global $con;
    
    $query = "
        SELECT 
            Status,
            COUNT(*) as count
        FROM tblcomplaints 
        WHERE IsActive = 1
        GROUP BY Status
    ";
    
    $result = mysqli_query($con, $query);
    $stats = [
        'Pending' => 0,
        'In Progress' => 0,
        'Resolved' => 0,
        'Closed' => 0
    ];
    
    if ($result) {
        while ($row = mysqli_fetch_assoc($result)) {
            $stats[$row['Status']] = (int)$row['count'];
        }
    }
    
    echo json_encode([
        'success' => true,
        'stats' => $stats
    ]);
}

// Get single complaint
function getComplaint($complaintId) {
    global $con;
    
    $complaintId = (int)$complaintId;
    $query = "
        SELECT 
            c.*,
            'Unknown Customer' as CustomerName,
            'N/A' as Mobile,
            'N/A' as Area,
            'N/A' as RiceBagName,
            'N/A' as Brand,
            'System' as CreatedByName,
            'N/A' as ResolvedByName
        FROM tblcomplaints c
        WHERE c.ID = $complaintId AND c.IsActive = 1
    ";
    
    $result = mysqli_query($con, $query);
    $complaint = mysqli_fetch_assoc($result);
    
    if (!$complaint) {
        echo json_encode(['success' => false, 'message' => 'Complaint not found']);
        return;
    }
    
    echo json_encode([
        'success' => true,
        'data' => $complaint
    ]);
}

// Create a new complaint
function createComplaint() {
    global $con, $userId;
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        echo json_encode(['success' => false, 'message' => 'Invalid JSON data']);
        return;
    }
    
    // Validate required fields
    if (!isset($input['customer_id']) || !isset($input['rice_bag_id']) || 
        !isset($input['complaint_title']) || !isset($input['complaint_description'])) {
        echo json_encode(['success' => false, 'message' => 'Missing required fields']);
        return;
    }
    
    try {
        // Generate complaint number
        $complaintNumber = 'COMP-' . date('Ymd') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
        
        // Check if complaint number already exists
        do {
            $checkQuery = "SELECT COUNT(*) as count FROM tblcomplaints WHERE ComplaintNumber = '" . mysqli_real_escape_string($con, $complaintNumber) . "'";
            $checkResult = mysqli_query($con, $checkQuery);
            $exists = mysqli_fetch_assoc($checkResult)['count'] > 0;
            if ($exists) {
                $complaintNumber = 'COMP-' . date('Ymd') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
            }
        } while ($exists);
        
        // Insert complaint
        $query = "
            INSERT INTO tblcomplaints 
            (ComplaintNumber, CustomerID, RiceBagID, ComplaintType, ComplaintTitle, 
             ComplaintDescription, ComplaintDate, ComplaintTime, Priority, CreatedBy, IsActive)
            VALUES (
                '" . mysqli_real_escape_string($con, $complaintNumber) . "',
                " . (int)$input['customer_id'] . ",
                " . (int)$input['rice_bag_id'] . ",
                '" . mysqli_real_escape_string($con, $input['complaint_type'] ?? 'Quality') . "',
                '" . mysqli_real_escape_string($con, $input['complaint_title']) . "',
                '" . mysqli_real_escape_string($con, $input['complaint_description']) . "',
                CURDATE(),
                CURTIME(),
                '" . mysqli_real_escape_string($con, $input['priority'] ?? 'Medium') . "',
                " . $userId . ",
                1
            )
        ";
        
        if (mysqli_query($con, $query)) {
            $complaintId = mysqli_insert_id($con);
            
            echo json_encode([
                'success' => true,
                'message' => 'Complaint registered successfully',
                'data' => [
                    'complaint_id' => $complaintId,
                    'complaint_number' => $complaintNumber
                ]
            ]);
        } else {
            throw new Exception('Database error: ' . mysqli_error($con));
        }
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}

// Update complaint
function updateComplaint() {
    global $con, $userId;
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input || !isset($input['complaint_id'])) {
        echo json_encode(['success' => false, 'message' => 'Complaint ID required']);
        return;
    }
    
    try {
        $complaintId = (int)$input['complaint_id'];
        $updateFields = [];
        
        // Build dynamic update query
        if (isset($input['status'])) {
            $updateFields[] = "Status = '" . mysqli_real_escape_string($con, $input['status']) . "'";
            
            if (in_array($input['status'], ['Resolved', 'Closed'])) {
                $updateFields[] = "ResolvedDate = CURDATE()";
                $updateFields[] = "ResolvedBy = " . $userId;
            }
        }
        
        if (isset($input['priority'])) {
            $updateFields[] = "Priority = '" . mysqli_real_escape_string($con, $input['priority']) . "'";
        }
        
        if (isset($input['resolution'])) {
            $updateFields[] = "Resolution = '" . mysqli_real_escape_string($con, $input['resolution']) . "'";
        }
        
        if (empty($updateFields)) {
            echo json_encode(['success' => false, 'message' => 'No fields to update']);
            return;
        }
        
        $updateFields[] = "UpdatedAt = NOW()";
        
        $query = "
            UPDATE tblcomplaints 
            SET " . implode(', ', $updateFields) . "
            WHERE ID = $complaintId AND IsActive = 1
        ";
        
        if (mysqli_query($con, $query)) {
            if (mysqli_affected_rows($con) > 0) {
                echo json_encode(['success' => true, 'message' => 'Complaint updated successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Complaint not found or no changes made']);
            }
        } else {
            throw new Exception('Database error: ' . mysqli_error($con));
        }
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}
?>