<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use CodeIgniter\Email\Email;
use App\Libraries\CSVReader;
use App\Models\UserModel; // Import the UserModel

class Home extends BaseController
{
    protected $userModel;

    public function __construct()
    {
        $this->userModel = new UserModel(); // Initialize the model globally
    }

public function index()
{
    if (!session()->get('logged_in')) {
        return redirect()->to('/login');
    }

    $db = \Config\Database::connect();

$data = [];

        return view('home', $data);
  
}


public function leasedocuments()
    {
 $session = session();
 
 if (!session()->get('logged_in')) {
        return redirect()->to('/login');
    }

        // Get session data
        $role_type = $session->get('role_type');
        $user_id = $session->get('user_id');

        // Get database connection
        $db = \Config\Database::connect();

        // Execute query
        $query = $db->query("SELECT * FROM saveddocs WHERE cid = ? ORDER BY dater DESC", [$user_id]);

        // Fetch results
        $data['task_list'] = $query->getResultArray();
        // Load view with data
        return view('leasedocuments', $data);
    }



 public function paynow()
    {
        // Load session service
        $session = session();
        
        if (!session()->get('logged_in')) {
        return redirect()->to('/login');
    }

        // Get session data
        $role_type = $session->get('role_type');
        $user_id = $session->get('user_id');

        // Get database connection
        $db = \Config\Database::connect();

        // Execute query
        $query = $db->query("SELECT * FROM payments ORDER BY dater DESC");

        // Fetch results
        $data['task_list'] = $query->getResultArray();

               return view('paynow', $data);

    }


   public function upload_pdf()
    {
        // Load helper
        helper(['form', 'filesystem']);

        // Get request instance
        $request = service('request');

        // File handling
        $file = $this->request->getFile('file');
        
        if (!$file->isValid() || $file->getExtension() !== 'pdf') {
            return $this->response->setJSON(['success' => false, 'message' => 'Invalid file. Only PDFs are allowed.']);
        }

        // Generate unique filename
        $newName = uniqid() . '_' . time() . '.' . $file->getExtension();

        // Move file to uploads directory
        if (!$file->move(ROOTPATH . 'public/uploads/documents/', $newName)) {
            return $this->response->setJSON(['success' => false, 'message' => 'File upload failed.']);
        }

        // Get POST data
        $docname = $request->getPost('docname');
        $type = $request->getPost('type');
        $cid = $request->getPost('cid');
        $dater = date('Y-m-d H:i:s');

        // Validate input
        if (empty($docname) || empty($type) || empty($cid)) {
            return $this->response->setJSON(['success' => false, 'message' => 'Invalid input data.']);
        }

        // Get database connection
        $db = \Config\Database::connect();

        // Insert into 'saveddocs' table
        $query = $db->query("INSERT INTO saveddocs (cid, docname, dater, type, filename) VALUES (?, ?, ?, ?, ?)", [
            $cid, $docname, $dater, $type, $newName
        ]);

        if ($query) {
            return $this->response->setJSON(['success' => true, 'message' => 'PDF uploaded and saved successfully.']);
        } else {
            return $this->response->setJSON(['success' => false, 'message' => 'Database insertion failed.']);
        }
    }

public function uploadpdf()
{
    helper(['form', 'filesystem', 'session']);

    $session = session();
    $request = service('request');
    $file = $this->request->getFile('file');
    
    if (!session()->get('logged_in')) {
        return redirect()->to('/login');
    }

    // Validate file
    if (!$file->isValid() || strtolower($file->getExtension()) !== 'pdf') {
        $session->set('error', 'Invalid file. Only PDF files are allowed.');
        return redirect()->back();
    }

    // Original file name and timestamped new name
    $originalName = pathinfo($file->getClientName(), PATHINFO_FILENAME);
    $timestamp = time();
    $newName = $originalName . '_' . $timestamp . '.pdf';

    // Create upload path
    $uploadPath = ROOTPATH . 'uploads/documents/';
    if (!is_dir($uploadPath)) {
        mkdir($uploadPath, 0755, true);
    }

    // Move file
    if (!$file->move($uploadPath, $newName)) {
        $session->set('error', 'Failed to upload the file.');
        return redirect()->back();
    }

    // Session user ID, document info
    $docname = $file->getClientName(); // original file name
    $type = 'client';
    $cid = $session->get('user_id');
    $dater = date('Y-m-d H:i:s');

    // Validate required inputs
    if (empty($docname) || empty($type) || empty($cid)) {
        $session->set('error', 'Missing required data.');
        return redirect()->back();
    }

    // Save file metadata to database
    $db = \Config\Database::connect();
    $builder = $db->table('saveddocs');
    $inserted = $builder->insert([
        'cid' => $cid,
        'docname' => $docname,
        'dater' => $dater,
        'type' => $type,
        'filename' => $newName
    ]);

    if ($inserted) {
        $session->set('message', 'PDF uploaded and saved successfully.');
    } else {
        $session->set('error', 'Database insertion failed.');
    }

    return redirect()->back();
}

public function stripePost()
{
    helper(['form', 'url', 'session']);
    $session = session();
    $request = service('request');

    require_once APPPATH . 'ThirdParty/stripe-php/init.php';

    \Stripe\Stripe::setApiKey(config('Stripe')->secretKey);

    $message = null;
    $success = false;
    $subscription = null;
    $err = null;
    $data = [];

    try {
        $timestamp = date('YmdHis');
        $orderid = $timestamp . '-' . mt_rand(1, 999);

        // Create Stripe customer
        $customer = \Stripe\Customer::create([
            'email' => $session->get('emailid'),
            'source' => $request->getPost('stripeToken'),
        ]);

        // Create subscription
        $subscription = \Stripe\Subscription::create([
            'customer' => $customer->id,
            'items' => [
                ['price' => $session->get('planid')],
            ],
            'metadata' => ['order_id' => $orderid],
        ]);

    } catch (\Stripe\Exception\CardException $e) {
        $err = $e->getError();
        $message = 'Card error: ' . $err->message;
    } catch (\Exception $e) {
        $message = 'Error: ' . $e->getMessage();
    }

    // Load model
    $productModel = new \App\Models\ProductModel();

    if ($subscription) {
        $subscriptionJson = $subscription->jsonSerialize();

        if ($subscriptionJson['status'] === 'active') {
            $productModel->save([
                'response' => json_encode($subscriptionJson),
                'amount' => $session->get('planamount'),
                'plan' => $session->get('plan'),
                'vid' => $session->get('vid'),
                'pid' => $session->get('pid'),
                'paddress' => $session->get('paddress'),
                'applicants' => $session->get('applicants'),
                'adults' => $session->get('adults'),
                'fees' => $session->get('fees'),
                'dater' => date('Y-m-d'),
                'status' => 'success',
                'order_id' => $orderid,
                'subscription_id' => $subscriptionJson['id'],
                'customer_id' => $customer->id,
                'plan_id' => $request->getPost('plan_id'),
                'subscription_status' => $subscriptionJson['status'],
                'start_date' => date('Y-m-d', $subscriptionJson['current_period_start']),
                'end_date' => date('Y-m-d', $subscriptionJson['current_period_end']),
                'next_billing_date' => date('Y-m-d', $subscriptionJson['current_period_end']),
                'cancel_at_period_end' => $subscriptionJson['cancel_at_period_end'],
            ]);

            $success = true;
            $message = 'Subscription created successfully.';

            // Retrieve user & property info
            $db = \Config\Database::connect();
            $vid = $session->get('vid');
            $pid = $session->get('pid');

            $uemail = '';
            $uemail22 = '';
            $eplan = $session->get('plan');

            if ($vid) {
                $row = $db->table('codeigniter_register')->where('id', $vid)->get()->getRow();
                $uemail = $row ? $row->email : '';
            }

            if ($pid) {
                $row2 = $db->table('properties')->where('id', $pid)->get()->getRow();
                $uemail22 = $row2 ? $row2->property_address : '';
            }

            // Send Email using PHPMailer
            $mail = new \PHPMailer\PHPMailer\PHPMailer(true);

            try {
                $mail->isSMTP();
                $mail->Host = 'upkeeproperty.com';
                $mail->SMTPAuth = true;
                $mail->Username = 'reachus@upkeeproperty.com';
                $mail->Password = 'yPcbCo(.gGV8';
                $mail->SMTPSecure = 'ssl';
                $mail->Port = 465;

                $mail->setFrom('reachus@upkeeproperty.com', 'UpkeeProperty');
                $mail->addAddress($session->get('emailid'));
                $mail->Subject = 'Subscription Successful';
                $mail->isHTML(true);

                $mail->Body = "
                    <p>Hi Landlord,</p>
                    <p>You have successfully subscribed to <strong>$eplan</strong> for your property at <strong>$uemail22</strong>.</p>
                    <p>Thank you,<br>UpkeeProperty Team</p>
                ";

                $mail->send();
            } catch (\Exception $mailEx) {
                log_message('error', 'Mail error: ' . $mailEx->getMessage());
            }

            $data = [
                'subscription_id' => $subscriptionJson['id'],
                'order_id' => $orderid,
            ];
        } else {
            $productModel->save([
                'response' => json_encode($subscriptionJson),
                'amount' => $session->get('planamount'),
                'plan' => $session->get('plan'),
                'vid' => $session->get('vid'),
                'pid' => $session->get('pid'),
                'dater' => date('Y-m-d'),
                'status' => 'failed'
            ]);
            $message = 'Subscription failed to activate.';
        }
    } else {
        $productModel->save([
            'response' => json_encode($err),
            'status' => 'failed',
            'dater' => date('Y-m-d'),
        ]);
    }

    return $this->response->setJSON([
        'success' => $success,
        'message' => $message,
        'data' => $data
    ]);
}


public function success(){
        if (!session()->get('logged_in')) {
        return redirect()->to('/login');
    }

    $db = \Config\Database::connect();

$data = [];

        return view('success', $data);
}

public function login()
{
    helper(['form']);

    if ($this->request->getPost('login')) {
        $email = $this->request->getPost('email');
        $password = $this->request->getPost('password');

        $db = \Config\Database::connect();

        // First, try from 'users'
        $user = $db->table('codeigniter_register')->where('email', $email)->get()->getRowArray();
        $usrtype = 'client';

       

        // Check password (md5)
        if ($user && $user['password'] === md5($password)) {
            session()->set([
                'user_id'   => $user['id'],
                'name'   => $user['name'],
                'user_email'     => $user['email'],
                'user_type' => $usrtype,
                'logged_in' => true
            ]);

            return redirect()->to('/');
        } else {
            return redirect()->back()->with('error', 'Invalid email or password');
        }
    }

    return view('login');
}

public function tenantpdf()
    {
 $session = session();
 
 if (!session()->get('logged_in')) {
        return redirect()->to('/login');
    }


        // Get database connection
        $db = \Config\Database::connect();

        // Execute query
        $query = $db->query("SELECT * FROM saveddocs WHERE cid = ? ORDER BY dater DESC", [$user_id]);

        // Fetch results
        $data['task_list'] = $query->getResultArray();
        // Load view with data
        return view('tenantpdf', $data);
    }

    public function logout()
    {
        session()->destroy();
        return redirect()->to('/login');
    }
}
