<?php
/**
 * POST /api/corporate/intake.php
 * حفظ مراحل طلب الشركة (1-5) بشكل تدريجي
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
$_kctx = Kernel::handle(['auth' => true, 'rate' => 'api']);
$_user = $_kctx['user']; $_userId = (int)$_user['id'];
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); die(json_encode(['error'=>'method_not_allowed'])); }

$b     = json_decode(file_get_contents('php://input'), true) ?? [];
$phase = (int)($b['phase'] ?? 0);
$ref   = preg_replace('/[^A-Z0-9\-]/', '', $b['ref'] ?? '');

if ($phase < 1 || $phase > 5) {
    http_response_code(400);
    die(json_encode(['error'=>'invalid_phase','message'=>'Phase must be 1-5']));
}

try {
    if ($phase === 1) {
        // Phase 1: Create new inquiry
        require_once '../../engine/CorporateAgent.php';
        $ref = CorporateAgent::generateRef();

        $st = db()->prepare(
            "INSERT INTO corporate_inquiries
             (ref_no, org_name, org_type, org_sector, employees_count,
              expected_users, operating_states, years_active, uses_ai, phase_completed, status)
             VALUES (?,?,?,?,?,?,?,?,?,1,'draft')"
        );
        $st->execute([
            $ref,
            mb_substr(trim($b['org_name'] ?? ''), 0, 200),
            in_array($b['org_type']??'', ['private','ngo','educational','group','other']) ? $b['org_type'] : 'private',
            mb_substr(trim($b['org_sector'] ?? ''), 0, 100),
            $b['employees_count'] ?? '',
            $b['expected_users'] ?? '',
            json_encode($b['operating_states'] ?? []),
            $b['years_active'] ?? '',
            (int)($b['uses_ai'] ?? 0),
        ]);

        echo json_encode(['ok'=>true,'ref'=>$ref,'phase'=>1,'next_phase'=>2,'progress'=>20]);

    } elseif ($phase === 2 && $ref) {
        db()->prepare(
            "UPDATE corporate_inquiries SET
             challenges_text=?, current_systems=?, pain_points=?,
             priority_challenge=?, phase_completed=GREATEST(phase_completed,2)
             WHERE ref_no=?"
        )->execute([
            mb_substr(trim($b['challenges_text']??''), 0, 1000),
            json_encode($b['current_systems'] ?? []),
            json_encode($b['pain_points'] ?? []),
            mb_substr(trim($b['priority_challenge']??''), 0, 300),
            $ref,
        ]);
        echo json_encode(['ok'=>true,'ref'=>$ref,'phase'=>2,'next_phase'=>3,'progress'=>40]);

    } elseif ($phase === 3 && $ref) {
        db()->prepare(
            "UPDATE corporate_inquiries SET services_selected=?,
             phase_completed=GREATEST(phase_completed,3) WHERE ref_no=?"
        )->execute([json_encode($b['services_selected'] ?? []), $ref]);
        echo json_encode(['ok'=>true,'ref'=>$ref,'phase'=>3,'next_phase'=>4,'progress'=>60]);

    } elseif ($phase === 4 && $ref) {
        $sla = in_array($b['sla_level']??'',['standard','professional','enterprise']) ? $b['sla_level'] : 'standard';
        db()->prepare(
            "UPDATE corporate_inquiries SET
             tech_requirements=?, sla_level=?, implementation_timeline=?,
             budget_min_usd=?, budget_max_usd=?, payment_preference=?, decision_maker=?,
             phase_completed=GREATEST(phase_completed,4) WHERE ref_no=?"
        )->execute([
            json_encode($b['tech_requirements'] ?? []),
            $sla,
            mb_substr($b['implementation_timeline']??'',0,50),
            max(0,(int)($b['budget_min_usd']??0)),
            max(0,(int)($b['budget_max_usd']??0)),
            mb_substr($b['payment_preference']??'',0,50),
            mb_substr($b['decision_maker']??'',0,50),
            $ref,
        ]);
        echo json_encode(['ok'=>true,'ref'=>$ref,'phase'=>4,'next_phase'=>5,'progress'=>80]);

    } elseif ($phase === 5 && $ref) {
        if (empty(trim($b['contact_name']??'')) || empty(trim($b['contact_email']??''))) {
            http_response_code(400);
            die(json_encode(['error'=>'contact_required']));
        }
        db()->prepare(
            "UPDATE corporate_inquiries SET
             contact_name=?, contact_title=?, contact_email=?, contact_phone=?,
             contact_whatsapp=?, preferred_contact=?, best_time=?, website=?,
             phase_completed=5, status='submitted', submitted_at=NOW()
             WHERE ref_no=?"
        )->execute([
            mb_substr(trim($b['contact_name']??''),0,150),
            mb_substr(trim($b['contact_title']??''),0,100),
            mb_substr(trim($b['contact_email']??''),0,200),
            mb_substr(trim($b['contact_phone']??''),0,30),
            mb_substr(trim($b['contact_whatsapp']??''),0,30),
            mb_substr(trim($b['preferred_contact']??''),0,50),
            mb_substr(trim($b['best_time']??''),0,100),
            mb_substr(trim($b['website']??''),0,200),
            $ref,
        ]);

        // Notify admin
        try {
            db()->prepare("INSERT INTO notifications (user_id,type,title,body,data) VALUES (1,'corporate_inquiry',?,?,?)")
               ->execute(["طلب جديد من {$b['org_name']}",'تقديم طلب حلول الشركات',json_encode(['ref'=>$ref])]);
        } catch (Throwable $ignored) {}

        echo json_encode(['ok'=>true,'ref'=>$ref,'phase'=>5,'progress'=>100,'status'=>'submitted']);
    } else {
        http_response_code(400);
        echo json_encode(['error'=>'invalid_request']);
    }

} catch (Throwable $e) {
    error_log("[corporate/intake] " . $e->getMessage());
    http_response_code(500);
    Logger::error('endpoint_error', ['error' => $e->getMessage()]);
    Kernel::fail('server_error', 'خطأ مؤقت — حاول مرة أخرى', 500);
}
